File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ # Time complexity = O(d*(n+b))
2+ # d = number of cycles
3+ # b = base value
4+
5+ # Space Complexity = O(n+b)
6+ # two auxiliary arrays of size b (base) and of size n (number of elements)
7+
8+ def countingSort (arr , exp1 ):
9+
10+ # n = size of the array
11+ n = len (arr )
12+
13+ # Initialize output array that will return sorted array
14+ output = [0 ] * (n )
15+
16+ # count array that store occurrences
17+ count = [0 ] * (10 )
18+
19+ # Loop through and store the count of number into array
20+ for i in range (0 , n ):
21+ index = (arr [i ]/ exp1 )
22+ count [int ((index )% 10 )] += 1
23+
24+ # Eg. count[0] will store counts of 0 in the array
25+ for i in range (1 ,10 ):
26+ count [i ] += count [i - 1 ]
27+
28+ # Output array building
29+ i = n - 1
30+ while i >= 0 :
31+ index = (arr [i ]/ exp1 )
32+ output [ count [ int ((index )% 10 ) ] - 1 ] = arr [i ]
33+ count [int ((index )% 10 )] -= 1
34+ i -= 1
35+
36+ # Copy array to output array
37+ i = 0
38+ for i in range (0 ,len (arr )):
39+ arr [i ] = output [i ]
40+
41+ def radixSort (arr ):
42+
43+ max1 = max (arr )
44+
45+ #Do counting sort for every digit. exp is 10^i where i is current digit
46+ exp = 1
47+ while max1 / exp > 0 :
48+ countingSort (arr ,exp )
49+ exp *= 10
50+
51+ # Driver code
52+
53+ # Using random generator to generate number ranging 1 - 30 and add into list
54+ import random
55+ randomlist = []
56+ for i in range (0 ,5 ):
57+ n = random .randint (1 ,30 )
58+ randomlist .append (n )
59+
60+ # Printing statement
61+ print ('Before sorting:' , randomlist )
62+
63+ radixSort (randomlist )
64+ print ('After sorting:' , randomlist )
You can’t perform that action at this time.
0 commit comments