Skip to content

Commit 3fc885f

Browse files
radix__sort.py
1 parent 03a4251 commit 3fc885f

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

sorts/radix__sort.py

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

0 commit comments

Comments
 (0)