Skip to content

Instantly share code, notes, and snippets.

@robbie01
Last active January 7, 2017 22:03
Show Gist options
  • Save robbie01/d47ffbe13e0170edc542a15004842232 to your computer and use it in GitHub Desktop.
Save robbie01/d47ffbe13e0170edc542a15004842232 to your computer and use it in GitHub Desktop.
LSD Radix sort implemented in Python 3 using base 10 (but can be easily modified to use any base)
base = 10
def radixsort(list):
maxPlace = max(len(int2base(i, base)) for i in list)
list = [(0, i) for i in list]
for i in range(1, maxPlace + 1):
list = [(FindInPlace(j, base, i), j) for _, j in list]
newList = []
for j in range(base):
newList += [k for k in list if k[0] == j]
list = newList
return [j for _, j in list]
def FindInPlace(number, base, place): # yoinked from http://stackoverflow.com/a/620699
return number//base**(place-1) % base
def int2base(x,b,alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): # yoinked from http://stackoverflow.com/a/2267721
if b<2 or b>len(alphabet):
if b==64:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
else:
raise AssertionError("int2base base out of range")
if isinstance(x,complex):
return ( int2base(x.real,b,alphabet) , int2base(x.imag,b,alphabet) )
if x<=0:
if x==0:
return alphabet[0]
else:
return '-' + int2base(-x,b,alphabet)
rets=''
while x>0:
x,idx = divmod(x,b)
rets = alphabet[idx] + rets
return rets
if __name__ == '__main__':
from sys import argv
from random import shuffle
list = list(range(int(argv[1])))
shuffle(list)
list = radixsort(list)
print(all(list[i] <= list[i+1] for i in range(len(list)-1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment