Skip to content

Commit c3d07ee

Browse files
committed
added radix sort
1 parent 54f5322 commit c3d07ee

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
def countingSort(array, place):
2+
size = len(array)
3+
output = [0] * size
4+
count = [0] * 10
5+
6+
# Calculate count of elements
7+
for i in range(0, size):
8+
index = array[i] // place
9+
count[index % 10] += 1
10+
11+
# Calculate cumulative count
12+
for i in range(1, 10):
13+
count[i] += count[i - 1]
14+
15+
# Place the elements in sorted order
16+
i = size - 1
17+
while i >= 0:
18+
index = array[i] // place
19+
output[count[index % 10] - 1] = array[i]
20+
count[index % 10] -= 1
21+
i -= 1
22+
23+
for i in range(0, size):
24+
array[i] = output[i]
25+
26+
27+
# Main function to implement radix sort
28+
def radixSort(array):
29+
# Get maximum element
30+
max_element = max(array)
31+
32+
place = 1
33+
while max_element // place > 0:
34+
countingSort(array, place)
35+
place *= 10
36+
37+
38+
data = [121, 432, 564, 23, 1, 45, 788]
39+
radixSort(data)
40+
print(data)

0 commit comments

Comments
 (0)