Last active
August 29, 2015 13:55
-
-
Save quintenpalmer/8741474 to your computer and use it in GitHub Desktop.
Radix sort with nice helper functions
This file contains 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
#!/usr/bin/env python | |
from math import log, ceil | |
def get_longest(array): | |
return int(ceil(log(max(array), 10))) | |
def get_digit(number,digit): | |
return number / (10 ** digit) % 10 | |
def get_bins(): | |
return [[] for i in range(10)] | |
def merge_bins(bins): | |
return [i for sub in bins for i in sub] | |
def sort_on_digit(array,digit): | |
bins = get_bins() | |
for number in array: | |
bins[get_digit(number, digit)].append(number) | |
return merge_bins(bins) | |
def radix_sort(array): | |
length = get_longest(array) | |
for digit in range(length + 1): | |
array = sort_on_digit(array, digit) | |
return array | |
if __name__ == '__main__': | |
import sys | |
array = range(30, -1, -1) | |
#array = [403, 25, 23, 1000, 800, 101, 16, 15, 2] | |
print radix_sort(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment