Created
July 10, 2012 12:54
-
-
Save mre/3083079 to your computer and use it in GitHub Desktop.
Radix Sort implementation in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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