Skip to content

Commit 083f657

Browse files
committed
Create radix_sort.py
added python implementation of radix sort
1 parent 5438853 commit 083f657

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

src/python/radix_sort.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
def radix_sort(arr):
2+
# Find the maximum number to know the number of digits
3+
max_num = max(arr)
4+
5+
# Do counting sort for every digit, starting from the least significant digit
6+
exp = 1
7+
while max_num // exp > 0:
8+
counting_sort(arr, exp)
9+
exp *= 10
10+
11+
12+
def counting_sort(arr, exp):
13+
n = len(arr)
14+
output = [0] * n
15+
count = [0] * 10
16+
17+
for i in range(n):
18+
index = arr[i] // exp
19+
count[index % 10] += 1
20+
21+
for i in range(1, 10):
22+
count[i] += count[i - 1]
23+
24+
i = n - 1
25+
while i >= 0:
26+
index = arr[i] // exp
27+
output[count[index % 10] - 1] = arr[i]
28+
count[index % 10] -= 1
29+
i -= 1
30+
31+
for i in range(n):
32+
arr[i] = output[i]
33+
34+
35+
def main():
36+
arr = [170, 2, 45, 75, 75, 90, 802, 24, 2, 66]
37+
print("Unsorted array:", arr)
38+
radix_sort(arr)
39+
print("Sorted array:", arr)
40+
41+
42+
if __name__ == "__main__":
43+
main()

0 commit comments

Comments
 (0)