sorting - Optimize LSD radix sort in python -


i'm trying implement lsd radix sort in python, code used 4 loop, there way can in 3 or less?


here 4 loops:

first loop iterate through input list, convert desired radix, , change each number reversed list, so:

123 --> [3,2,1] 

second loop iterate through newly created list, make them have same length adding 0, add pointer corresponding element in input list, reverse list.like this:

input: [1234, 56, 7] after first loop: [[4, 3, 2, 1], [6, 5], [7]] after second loop: [[0, 1, 2, 3, 4], [1, 0, 0, 5, 6], [2, 0, 0, 0, 7]] 

third loop sort element in lsd order using counting sort, code below.

fourth loop put every thing in new list sorted order using pointers.

here's code radix sort:

def radix_sort(collection, radix):      new_collect = []     max_len = 0      #loop through collection, convert them desired form , put in new_collect     in collection:         num = []         while >= radix:             remain = % radix             num.append(remain)             = // radix         num.append(i)         new_collect.append(num)          if len(num) > max_len:             max_len = len(num)      #loop through new_collect, extend each item same length     in range(0, len(new_collect)):         space = max_len - len(new_collect[i])         patch = [0 j in range(space)]         new_collect[i].extend(patch)          #add pointer corresponding element in collection         new_collect[i].append(i)         new_collect[i].reverse()      #sort digit counting_sort     in range(-1, -1 - max_len, -1):         new_collect = counting_sort(new_collect, radix - 1, i)      #create new list same length collection     return_list = list(range(len(collection)))      #put elements in collection return_list, using pointer in new_collect     in range(0, len(collection)):         return_list[i] = collection[new_collect[i][0]]      return return_list 

and here code counting sort:

def counting_sort(collection, d_range, digit = -1):      d_range += 1      b = list(range(len(collection) + 1))     c = list(range(d_range))      in range(d_range):         c[i] = 0      j in collection:         #c[j] = |{key = j}|         c[j[digit]] += 1      in range(1, d_range):         #c[i] = |{key <= i}|         c[i] = c[i] + c[i - 1]      in range(len(collection) - 1, -1, -1):         b[c[collection[i][digit]]] = collection[i]         c[collection[i][digit]] -= 1          return b[1:] 


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -