CodexBloom - Programming Q&A Platform

implementing Implementing a Radix Sort in Python: Unexpected Infinite Loop

πŸ‘€ Views: 65 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-03
python sorting-algorithms radix-sort Python

I'm stuck trying to I'm collaborating on a project where I'm attempting to set up I'm having a hard time understanding Hey everyone, I'm running into an issue that's driving me crazy... This might be a silly question, but I'm trying to implement a Radix Sort algorithm in Python to sort a list of integers, but I keep running into an infinite loop that I need to seem to debug... My implementation is based on the least important digit (LSD) method, and I'm using a stable counting sort as a subroutine. Here’s my current code: ```python def counting_sort(array, exp): n = len(array) output = [0] * n count = [0] * 10 for i in range(n): index = (array[i] // exp) % 10 count[index] += 1 for i in range(1, 10): count[i] += count[i - 1] for i in range(n - 1, -1, -1): index = (array[i] // exp) % 10 output[count[index] - 1] = array[i] count[index] -= 1 for i in range(n): array[i] = output[i] def radix_sort(array): max1 = max(array) exp = 1 while max1 // exp > 0: counting_sort(array, exp) exp *= 10 arr = [170, 45, 75, 90, 802, 24, 2, 66] radix_sort(arr) print(arr) ``` When I run this code, it seems to get exploring in the `while` loop in the `radix_sort` function, but I'm not sure why. I've checked the condition `max1 // exp > 0` and it looks correct at first, but it appears that `exp` is never reaching a point where that condition fails. I suspect it might have something to do with how I'm handling the output of the counting sort or the way `exp` is being incremented. I've verified that `max1` is indeed 802 for the example list, so I'm expecting the loop to break after processing the important digits. Can anyone provide insights on what might be going wrong here? Any tips on debugging this kind of scenario would also be appreciated! My development environment is macOS. What's the best practice here? I'm working on a CLI tool that needs to handle this. Any ideas what could be causing this? I'm working in a Windows 10 environment. Could someone point me to the right documentation? Thanks for taking the time to read this! What am I doing wrong? I'm on Debian using the latest version of Python. The project is a web app built with Python. Any pointers in the right direction?