What is wrong with this quicksort implementation?

I am trying to implement a quicksort algorithm that selects a bar as the right-most element, as described in Cormey et al., Introduction to Algorithms:

enter image description here

Here is my Python implementation:

def partition(A, p, r):
    pivot = A[r]
    i = p - 1
    for j in range(p, r-1):
        if A[j] < pivot:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i+1], A[r] = A[r], A[i+1]
    return i+1

def quicksort(A, p, r):
    if p < r:
        q = partition(A, p, r)
        quicksort(A, p, q-1)
        quicksort(A, q+1, r)

However, if I try to check it like this:

A = [2, 8, 7, 1, 3, 5, 6, 4]
quicksort(A, 0, len(A)-1)
print(A)

I get an array that is not sorted, but simply partitioned once:

[2, 3, 1, 4, 5, 7, 8, 6]

(That is, all elements on the left (right) are 4smaller (larger) than it). It seems that recursive calls quicksortdo not work on the input array A, like a call partition. How can i fix this?

+4
source share
1 answer

partition, for j in range(p, r-1):: , for j in range(p, r):.

, Python , r-1, r, r-1.

+5

Source: https://habr.com/ru/post/1683594/


All Articles