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?
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))
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments