Skip to content

Commit ce7d8a2

Browse files
Create RadixSort.py
1 parent 4eb93a8 commit ce7d8a2

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

RadixSort.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
def countingSort(arr, exp1):
2+
3+
n = len(arr)
4+
5+
# The output array elements that will have sorted arr
6+
output = [0] * (n)
7+
8+
# initialize count array as 0
9+
count = [0] * (10)
10+
11+
# Store count of occurrences in count[]
12+
for i in range(0, n):
13+
index = (arr[i]/exp1)
14+
count[int((index)%10)] += 1
15+
16+
# Change count[i] so that count[i] now contains actual
17+
# position of this digit in output array
18+
for i in range(1,10):
19+
count[i] += count[i-1]
20+
21+
# Build the output array
22+
i = n-1
23+
while i>=0:
24+
index = (arr[i]/exp1)
25+
output[ count[ int((index)%10) ] - 1] = arr[i]
26+
count[int((index)%10)] -= 1
27+
i -= 1
28+
29+
# Copying the output array to arr[],
30+
# so that arr now contains sorted numbers
31+
i = 0
32+
for i in range(0,len(arr)):
33+
arr[i] = output[i]
34+
35+
# Method to do Radix Sort
36+
def radixSort(arr):
37+
38+
# Find the maximum number to know number of digits
39+
max1 = max(arr)
40+
41+
# Do counting sort for every digit. Note that instead
42+
# of passing digit number, exp is passed. exp is 10^i
43+
# where i is current digit number
44+
exp = 1
45+
while max1/exp > 0:
46+
countingSort(arr,exp)
47+
exp *= 10
48+
49+
# Driver code to test above
50+
arr = [ 170, 45, 75, 90, 802, 24, 2, 66]
51+
radixSort(arr)
52+
53+
for i in range(len(arr)):
54+
print(arr[i]),

0 commit comments

Comments
 (0)