Skip to content

Instantly share code, notes, and snippets.

@mre
Created July 10, 2012 12:54
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mre/3083079 to your computer and use it in GitHub Desktop.
Save mre/3083079 to your computer and use it in GitHub Desktop.
Radix Sort implementation in Python
from math import log10
from random import randint
def get_digit(number, base, pos):
return (number // base ** pos) % base
def prefix_sum(array):
for i in range(1, len(array)):
array[i] = array[i] + array[i-1]
return array
def radixsort(l, base=10):
passes = int(log10(max(l))+1)
output = [0] * len(l)
for pos in range(passes):
count = [0] * base
for i in l:
digit = get_digit(i, base, pos)
count[digit] +=1
count = prefix_sum(count)
for i in reversed(l):
digit = get_digit(i, base, pos)
count[digit] -= 1
new_pos = count[digit]
output[new_pos] = i
l = list(output)
return output
l = [ randint(1, 99999) for x in range(100) ]
sorted = radixsort(l)
print sorted
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment