Skip to content

Instantly share code, notes, and snippets.

@neonb88
Created April 24, 2019 00:54
Show Gist options
  • Save neonb88/75dd5d6dad35bc85f0d726e246822b63 to your computer and use it in GitHub Desktop.
Save neonb88/75dd5d6dad35bc85f0d726e246822b63 to your computer and use it in GitHub Desktop.
# based off of https://gist.github.com/rizkyabdilah/1740053 ; resolved the case radix_sort([10000, 1000, 100, 10, 0])
def radix_sort(random_list):
'''
LSD (Least Significant Digit)
I think this works only on positive integers
'''
max_num_digs=-float('inf') # make sure we get to the max 10s place of the numbers within "random_list"
for e in random_list:
if e==0: # was giving -inf when we took log(0)
n_digs=1
else:
n_digs=int(np.floor(np.log10(e))) + 1
if n_digs > max_num_digs:
max_num_digs=n_digs
len_random_list = len(random_list)
modulus = 10
div = 1
while True:
# empty array, [[] for i in range(10)]
n_digits=10 # "10" b/c we're using decimal (for hex, it would be 16, etc.)
new_list = [[] for i in range(n_digits)]
# queue-based implementation
for value in random_list:
least_digit = value % modulus
least_digit /= div
new_list[least_digit].append(value)
modulus = modulus * 10
div = div * 10
if len(new_list[0]) == len_random_list and div==10**(max_num_digs+1):
return new_list[0]
random_list = []
for x in new_list:
for y in x:
random_list.append(y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment