Skip to content

Commit 93e97d7

Browse files
authored
radixSort.py
sir this is python code for Radix Sort
1 parent 9629aef commit 93e97d7

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

radixSort.py

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

0 commit comments

Comments
 (0)