I'm trying to implement the quicksort algorithm, but I keep getting list index out of range.
What exactly is out of range at quicksort(array, left, Pi vot-1)?
def partition(array,left,right):
#If pivot is not on leftmost, swap to make it leftmost
Pivot = array[0]
i = left+1
for j in range(i,right):
if array[j] < Pivot:
#Swap array[j] and array[i]
array[j], array[i] = array[i], array[j]
i += 1;
#Swap pivot and A[i-1]
array[Pivot], array[i-1] = array[i-1], array[Pivot]
return Pivot
def quicksort(array,left,right):
# Base case
if len(array) <= 1:
return array
#Choose pivot
Pivot = partition(array,left,right);
#Partition array around a pivot
#Recursive call
quicksort(array, left, Pivot-1)
quicksort(array, Pivot + 1, right)
print quicksort([1,5,3,4,9,10],0,5)
Error messages:
File "quicksort.py", line 25, in <module>
print quicksort([1,5,3,4,9,10],0,5)
File "quicksort.py", line 22, in quicksort
quicksort(array, left, Pivot-1)
File "quicksort.py", line 22, in quicksort
quicksort(array, left, Pivot-1)
File "quicksort.py", line 19, in quicksort
Pivot = partition(array,left,right);
File "quicksort.py", line 11, in partition
array[Pivot], array[i-1] = array[i-1], array[Pivot]
IndexError: list index out of range