QuickSort Algorithm Problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jollyfolly
    New Member
    • Sep 2009
    • 2

    QuickSort Algorithm Problem

    Could you please help me find the error. I myself have (i might be wrong) boiled it down to the for loop because it somehow magically converts a list into an int and tries to iterate over that. But I don't know how to fix it, doesn't even make sense why it would do it. Please help me out. Thanks in advance!

    Here is the error it gives me:

    TypeError: 'int' object is not iterable


    Here is my code:

    Code:
    import random
    unsortedlist = range(0,10)
    random.shuffle(unsortedlist)
    print unsortedlist
    
    def quickSort(ML):
        if ML == []:
            return []
        else:        
            rdex = random.randint(0, (len(ML)-1)) # chose a random index for pivot
            p = ML[rdex] # get the actual pivot integer
            LL, GL = [],[] 
            if len(ML) == 1: 
                return ML        
            else:
                del ML[rdex]
                for i in ML:
                    if i < p:
                        LL.append(i)
                    else:
                        GL.append(i)
                return quickSort(LL) + list(p) + quickSort(GL) 
    
    if __name__ == '__main__':
        print quickSort(unsortedlist)
  • YarrOfDoom
    Recognized Expert Top Contributor
    • Aug 2007
    • 1243

    #2
    What are you trying to use list() on an integer?

    Comment

    • jollyfolly
      New Member
      • Sep 2009
      • 2

      #3
      I fixed it, thanks. I guess I was looking in the wrong place and made 1 wrong assumption. Because I wanted to concatenate everything into a list, and "+" only accepts lists/strings I wanted to change the int p into a list that contains an int p. Seems like I too hastily made the analogy from using simply scheme (lisp) where you can do it by saying list(x). Python does take some stuff from scheme though. But for this particular problem it looks like to achieve the same in python you have to use the square brackets around something.

      Comment

      • Glenton
        Recognized Expert Contributor
        • Nov 2008
        • 391

        #4
        I haven't looked in detail at what you're writing, but the bisect module might be worth looking at?

        Comment

        Working...