Skip to content

Commit 9abfd8c

Browse files
committedOct 19, 2022
Added Radix sort
1 parent 26a5d70 commit 9abfd8c

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
 

‎Radix_sort.py

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

0 commit comments

Comments
 (0)
Please sign in to comment.