forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
radix_sort.py
55 lines (41 loc) · 1.14 KB
/
radix_sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import random
def radix_sort(arr):
# Find the maximum number to know the number of digits
max_num = max(arr)
# Do counting sort for every digit, starting from the least significant digit
exp = 1
while max_num // exp > 0:
counting_sort(arr, exp)
exp *= 10
def counting_sort(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 main():
print("Fixed Testing Array")
arr = [170, 2, 45, 75, 75, 90, 802, 24, 2, 66]
print("Unsorted array:", arr)
radix_sort(arr)
print("Sorted array:", arr)
print("Random Testing Array")
arr = []
for i in range(0, 10):
arr.append(random.randint(0, 20))
print("Unsorted array:", arr)
radix_sort(arr)
print("Sorted array:", arr)
if __name__ == "__main__":
main()