Question

i just write another radix sort program, here is my code:

#----------radix sort----------
def set_output():
    output_list = []
    for i in range (10):
        output_list.append(queue())
    return output_list

def set_radix(lists):
    output_list = set_output()
    for queue in lists:
        for num in queue:
            a = num[2]
            output_list[int(a)].add(num)
    return output_list

def sec_radix(input_list, i):
    output_list = set_output()
    for queue in input_list:
        while len(queue) > 0:
            num = queue.after()
            a = num[i]
            output_list[int(a)].add(num)
    return output_list

def done_radix(num_list):
    return sec_radix(sec_radix(set_radix(num_list), 1), 0)

the python shell keeps telling me that "IndexError: string index out of range", my string of numbers is all right. i think something wrong with my def set_radix()function, but i can't find out where is it?

Was it helpful?

Solution

Here is a radix sort coded so someone reasonable can understand it. I stole most of it from here.

def radixsort( aList ):
  RADIX = 10
  maxLength = False
  tmp , placement = -1, 1

  while not maxLength:
    maxLength = True
    # declare and initialize buckets
    buckets = [list() for _ in range( RADIX )]

    # split aList between lists
    for  i in aList:
      tmp = i // placement
      print ("i is " , i)
      print ("placement is " , placement)
      print ("tmp is ", tmp)
      print ("tmp % RADIX is ", tmp % RADIX)
      buckets[tmp % RADIX].append( i )
      if maxLength and tmp > 0:
        maxLength = False

    # empty lists into aList array
    a = 0
    for b in range( RADIX ):
      buck = buckets[b]
      for i in buck:
        aList[a] = i
        a += 1

    # move to next digit
    placement *= RADIX
  return aList



a = radixsort([18,5,100,3,1,19,6,0,7,4,2])
print(a)

The code on the site I got it from had some issues arising from % yielding a float. I suspect differences from python 2 to 3.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top