Python,
pasted
on Jan 19:
|
from math import log
def getDigit(n, b, k):
return (n // b ** k) % b # pulls the selected digit
def mkBlanks(k):
return [ [] for i in range(k) ] # create a list of empty lists to hold the split by digit
def split(l, b, k):
x = mkBlanks(b)
for i in l:
x[getDigit(i, b, k)].append(i) # append the number to the list selected by the digit
return x
def merge(x): # concatenate the lists back in order for the next step
l = []
for sublist in x:
for item in sublist:
l.append(item)
return l
def maxAbs(l):
return max(abs(x) for x in l) # largest abs value element of a list
def radixSort(l, b):
passes = int(log(maxAbs(l), b) + 1) # there are as many passes as there are digits in the longest number
t = list(l)
for i in range(passes):
t = merge(split(t, b, i))
return t
print radixSort([170, 45, 75, -90, 2, 24, -802, 66], 10) ;
|
Output:
|
[2, 24, 45, 66, 75, 170, -802, -90]
|
|