Skip to content

Commit 1c73e2d

Browse files
committed
added radix sort program
1 parent 2241aee commit 1c73e2d

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ In case, the list becomes too big in the future you can use `cmd + f` or `ctrl +
3636
- [Insertion Sort](./sorting/insertionsort.py)
3737
- [Merge Sort](./sorting/mergesort.py)
3838
- [Quick Sort](./sorting/quicksort.py)
39+
- [Radix Sort](./sorting/radixsort.py)
3940
- [Selection Sort](./sorting/selectionsort.py)
4041
- [Other Programs](./otherprograms)
4142
- [Armstrong number or not](./otherprograms/armstrongnumber.py)

sorting/radixsort.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
def radix_sort(arr):
2+
# Find the maximum number to determine the number of digits
3+
max_num = max(arr)
4+
5+
# Perform counting sort for every digit
6+
exp = 1
7+
while max_num // exp > 0:
8+
counting_sort(arr, exp)
9+
exp *= 10
10+
11+
def counting_sort(arr, exp):
12+
n = len(arr)
13+
output = [0] * n
14+
count = [0] * 10
15+
16+
# Store the count of each digit in count[]
17+
for i in range(n):
18+
index = arr[i] // exp
19+
count[index % 10] += 1
20+
21+
# Change count[i] so that count[i] contains the actual position
22+
# of this digit in output[]
23+
for i in range(1, 10):
24+
count[i] += count[i - 1]
25+
26+
# Build the output array
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+
# Copy the output array to arr[] so that arr[] contains sorted numbers
35+
for i in range(n):
36+
arr[i] = output[i]
37+
38+
# Enter user inputs in an array
39+
n = int(input("Enter the number of elements: "))
40+
arr = []
41+
for i in range(n):
42+
a = int(input("Enter element: "))
43+
arr.append(a)
44+
print()
45+
46+
print("Unsorted Array:", arr)
47+
radix_sort(arr)
48+
print("Sorted array:", arr)

0 commit comments

Comments
 (0)