Skip to content

Instantly share code, notes, and snippets.

@EdisonChendi
Last active May 27, 2018 08:51
Show Gist options
  • Save EdisonChendi/bf0ed61231a8717560d9685411f34a84 to your computer and use it in GitHub Desktop.
Save EdisonChendi/bf0ed61231a8717560d9685411f34a84 to your computer and use it in GitHub Desktop.
radix sort in python
#coding:UTF-8
from random import randint
from functools import partial
from counting_sort import counting_sort
'''
for simplicity: use base 10
b - base
k - range of values of keys of the input
O((n+b)*lgb k)
when b = n, the above expression is minimized => O(n*lgn k)
'''
def radix_sort(arr, n, k):
def get_int_pos(i, p):
try:
return int(str(i)[-p])
except IndexError:
return 0
sorted_arr = arr
for i in range(1, len(str(k))+1): # sort on each digit
# *this step must be stable*
sorted_arr = counting_sort(sorted_arr, n, k, key=partial(get_int_pos, p=i))
return sorted_arr
if __name__ == '__main__':
n = 10
k = 1000
arr = [randint(0, k) for i in range(n)]
sorted_arr = radix_sort(arr, n, k)
print("arr: {}".format(arr))
print("sorted_arr: {}".format(sorted_arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment