Radix Sort
# LSD
def counting_sort(arr, exp):
n = len(arr)
output = [0] * n
count = [0] * 10
# count the occurrences
for i in range(n):
index = (arr[i] // exp) % 10
count[index] += 1
# accumulated with previous
for i in range(1, 10):
count[i] += count[i - 1]
i = n - 1
while i >= 0:
index = (arr[i] // exp) % 10
output[count[index] - 1] = arr[i]
count[index] -= 1
i -= 1
for i in range(n):
arr[i] = output[i]
def radix_sort(arr):
max_value = max(arr)
exp = 1
# radix sort from low digit to high digit
while max_value // exp > 0:
counting_sort(arr, exp)
exp *= 10
# Example
data = [170, 45, 75, 90, 802, 24, 2, 66]
print("Original:", data)
radix_sort(data)
print("After:", data)
# Original: [170, 45, 75, 90, 802, 24, 2, 66]
# After: [2, 24, 45, 66, 75, 90, 170, 802]
Complexity
Type | Complexity |
---|---|
Time | O(n * k) |
Space | O(n) |
Stability
Stable