Skip to content

Commit 15e23d0

Browse files
authored
Merge pull request larymak#247 from tamilselvi53/dsa
Added Radix sort
2 parents 3765784 + 8db30e0 commit 15e23d0

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

Data Structures and Algorithms/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,8 @@
3939
- Selection Sort
4040

4141
- Binary Tree traversal
42+
43+
- Radix Sort (for numbers) using Counting Sort
44+
1. Find the largest number int given array. It has n digits. Therefore, the loop should go up to hundreds place (n times)
45+
2. It is stable sorting algorithm
46+
3. Sort the elements based on the unit place digits, then tenth place digits ... nTh place digits
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)