Skip to content

Instantly share code, notes, and snippets.

@anbnyc
Last active February 18, 2017 23:09
Show Gist options
  • Save anbnyc/a1e88a27f86565752cebc38019117cc1 to your computer and use it in GitHub Desktop.
Save anbnyc/a1e88a27f86565752cebc38019117cc1 to your computer and use it in GitHub Desktop.
Implementation of radix sort in Python
import math
import functools
""" radix_sort
in: list_to_sort (list)
in: base (optional)
out: sorted list_to_sort
"""
def radix_sort(list_to_sort,base=10):
# number of significant digits of largest number
sig_digits = math.ceil(math.log(max(list_to_sort),base))
""" recurse
in: list_to_sort (list)
in: i (int): significant digit we are on
out: list_to_sort (base case) or call to itself
"""
def recurse(list_to_sort,place):
if place == sig_digits:
return list_to_sort
else:
# one list per available digit in this base
all_digits = [[] for i in base]
# sort each number according to the digit in place position
for number in list_to_sort:
all_digits[math.floor(number % base**(place+1) / base**place)].append(number)
return recurse(functools.reduce(lambda a,b: a+b,all_digits),place+1)
return recurse(list_to_sort,0)
""" tests
"""
def tests():
print(radix_sort([1,15,104,207,381,245,76,72,173]))
print(radix_sort([1001,1101,1010,10,110,1011],2))
tests()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment