0

I was implementing quicksort in python

#QuickSort python

def sort(array):

    leftside = []
    rightside = []
    equal = []

    pivot = array[0]

    if (len(array)>1):
        for item in array:
            if item < pivot:
                leftside.append(item)
            if item > pivot:
                rightside.append(item)
            if item == pivot:
                equal.append(item)
    else:
        print array


    print sort(leftside) + equal + sort(rightside)

array = [1,2,5,4,6,2,3]
sort(array)

I get the error "pivot = array[0] IndexError: list index out of range", I don't see anything that could cause out of index error in this code. Could you please take a look?

Joseph D.
  • 11,804
  • 3
  • 34
  • 67
tori
  • 3
  • 2

1 Answers1

0

pivot = array[0] should be in if (len(array)>1):. Otherwise you may try to do it on an empty array.

Made some other quick fixes. See how this works:

#QuickSort python

def sort(array):

    leftside = []
    rightside = []
    equal = []

    if (len(array)>1):
        pivot = array[0]
        for item in array:
            if item < pivot:
                leftside.append(item)
            if item > pivot:
                rightside.append(item)
            if item == pivot:
                equal.append(item)
        return sort(leftside) + equal + sort(rightside)
    else:
        return array


array = [1,2,5,4,6,2,3]
print(sort(array))
stanleyli
  • 1,427
  • 1
  • 11
  • 28
  • Ah, Thanks for the answer. But, when I do that, I get "RuntimeError: maximum recursion depth exceeded". – tori May 20 '17 at 00:10
  • @tori Yes, I realized that -- tried to fix some other issues for you. Please refer to something like http://interactivepython.org/courselib/static/pythonds/SortSearch/TheQuickSort.html to see how others write quicksort in Python – stanleyli May 20 '17 at 00:14