SwadhyAI Notes

All Python notes

Radix Sort in Python đŸ—ī¸

Digit by Digit

Radix sort avoids comparison by creating and distributing elements into buckets according to their radix.

đŸ’ģ Implementation

python
def counting_sort_for_radix(arr, exp):
    n = len(arr)
    output = [0] * n
    count = [0] * 10

    for i in range(n):
        index = arr[i] // exp
        count[index % 10] += 1

    for i in range(1, 10):
        count[i] += count[i - 1]

    i = n - 1
    while i >= 0:
        index = arr[i] // exp
        output[count[index % 10] - 1] = arr[i]
        count[index % 10] -= 1
        i -= 1

    for i in range(n):
        arr[i] = output[i]

def radix_sort(arr):
    max_val = max(arr)
    exp = 1
    while max_val // exp > 0:
        counting_sort_for_radix(arr, exp)
        exp *= 10

arr = [170, 45, 75, 90, 802, 24, 2, 66]
radix_sort(arr)
print(arr)

🎮 Interactive Radix Sort Demo

Speed:
â„šī¸ Ready
Array
Buckets (0-9)
0
1
2
3
4
5
6
7
8
9

💡 Use Case

Useful for sorting integers or strings with fixed length. Complexity: O(nk).