2

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
2
  • Post the Error message.. Commented Jul 14, 2015 at 6:19
  • @KhalilAmmour-خليلعمورError messages added Commented Jul 14, 2015 at 6:23

3 Answers 3

3

In partition(),

Pivot = array[0]

Here Pivot looks like the value of pivot element. However,

#Swap pivot and A[i-1]        
array[Pivot], array[i-1] = array[i-1], array[Pivot]

Here you use it as index to array. Thus it's very likely to be out of legal array index range.

Sign up to request clarification or add additional context in comments.

Comments

2

During third iteration the value of pivot and array are as below

[10, 1, 3, 4, 9, 5] 10

In which you try to get array[Pivot]

Since it has only six elements ,So only the index out of range error is thrown

Comments

2

May be this may help.

def partition(array, begin, end):
    pivot = begin
    for i in xrange(begin+1, end+1):
        if array[i] <= array[begin]:
            pivot += 1
            array[i], array[pivot] = array[pivot], array[i]
    array[pivot], array[begin] = array[begin], array[pivot]
    return pivot


def quicksort(array, begin=0, end=None):
    if end is None:
        end = len(array) - 1
    if begin >= end:
        return
    pivot = partition(array, begin, end)
    quicksort(array, begin, pivot-1)
    quicksort(array, pivot+1, end)

1 Comment

add return in quicksort()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.