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).