Skip to content

Commit e29cad9

Browse files
committed
radix sort.py
1 parent 2a65016 commit e29cad9

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Practice Concepts/Sorting/counting-sort.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def countingsort(array):
2626
for i in range(0, size):
2727
array[i] = output[i]
2828

29-
29+
# Driver Code
3030
data = [4, 2, 2, 8, 3, 3, 1]
3131
countingsort(data)
3232
print("Sorted Array in Ascending Order: ")
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Python implementation of Radix Sort Algorithm
2+
3+
# Using Counting Sort to sort the elements on the basis of significant places
4+
def countingsort(array, place):
5+
size = len(array)
6+
output = [0] * size
7+
count = [0] * 10
8+
9+
# Calculate the count of elements
10+
for i in range(0, size):
11+
index = array[i] // place
12+
count[index % 10] += 1
13+
14+
# Calculate the cumulative count
15+
for i in range(1, 10):
16+
count[i] += count[i - 1]
17+
18+
# Place the elements in sorted order
19+
i = size - 1
20+
while i >= 0:
21+
index = array[i] // place
22+
output[count[index % 10] - 1] = array[i]
23+
count[index % 10] -= 1
24+
i -= 1
25+
26+
for i in range(0, size):
27+
array[i] = output[i]
28+
29+
# 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+
# Driver Code
41+
data = [121, 432, 564, 23, 1, 45, 788]
42+
radixsort(data)
43+
print(data)

0 commit comments

Comments
 (0)