File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change 1+ # Sorting Type: Radix
2+ #
3+ # Description: Radix sort is a sorting technique that
4+ # sorts the elements by first grouping the individual
5+ # digits of same place value. Then, sort the elements
6+ # according to their increasing/decreasing order.
7+
8+ from math import log10
9+ from random import randint
10+
11+ def get_num (num , base , pos ):
12+ return (num // base ** pos ) % base
13+
14+ def prefix_sum (array ):
15+ for i in range (1 , len (array )):
16+ array [i ] = array [i ] + array [i - 1 ]
17+ return array
18+
19+ def radixsort (l , base = 10 ):
20+ passes = int (log10 (max (l ))+ 1 )
21+ output = [0 ] * len (l )
22+
23+ for pos in range (passes ):
24+ count = [0 ] * base
25+
26+ for i in l :
27+ digit = get_num (i , base , pos )
28+ count [digit ] += 1
29+
30+ count = prefix_sum (count )
31+
32+ for i in reversed (l ):
33+ digit = get_num (i , base , pos )
34+ count [digit ] -= 1
35+ new_pos = count [digit ]
36+ output [new_pos ] = i
37+
38+ l = list (output )
39+ return output
40+
41+ l = [ randint (1 , 99999 ) for x in range (100 ) ]
42+ sorted = radixsort (l )
43+ print (sorted )
You can’t perform that action at this time.
0 commit comments