Skip to content

Commit a28674a

Browse files
authored
Merge pull request #339 from MrWeast/feature/radix-sort-python
Create radix_sort.py
2 parents 5438853 + 506ae67 commit a28674a

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3276,8 +3276,8 @@ In order to achieve greater coverage and encourage more people to contribute to
32763276
</a>
32773277
</td>
32783278
<td> <!-- Python -->
3279-
<a href="./CONTRIBUTING.md">
3280-
<img align="center" height="25" src="./logos/github.svg" />
3279+
<a href="./src/python/radix_sort.py">
3280+
<img align="center" height="25" src="./logos/python.svg" />
32813281
</a>
32823282
</td>
32833283
<td> <!-- Go -->

src/python/radix_sort.py

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

0 commit comments

Comments
 (0)