简体   繁体   中英

What is wrong with my python recursive quick sort algorithm?

So my algorithm has two functions. The first is partition which takes the first element of the list as the pivot and places all elements larger than it after it and all the smallest before it and I have tested it and it works just fine. The second function quicksort function and it uses partition recursively to sort the entire list. When I run the code in pycharm it says maximum recursion depth exceeded and a few other errors. Here is the code:

arr = [81, 4, 73, 1, 98, 69, 300, 14, 7, 420, 190, 8, 9]


def partition(low, high):
    lo = low
    hi = high
    pivot = arr[lo]
    while lo < hi:
        while arr[lo] <= pivot:
            lo += 1
        while arr[hi] > pivot:
            hi -= 1
        if hi > lo:
            arr[lo], arr[hi] = arr[hi], arr[lo]
    arr[0], arr[hi] = arr[hi], arr[0]
    return hi


def quicksort(l, h):
    if l < h:
        j = partition(l, h)
        quicksort(l, j)
        quicksort(j + 1, h)


quicksort(0, 12)
print(arr)

PS: I'm a beginner (only 2 months of python) so please try to explain simply. Thanks in advance!

Your partition function is flawed. Also, you should make your functions more flexible/reusable by passing a reference to the list rather than working on a global variable. Here's my implementation using the Hoare algorithm and a different way to select the pivot:

def partition(A, lo, hi):
    pivot = A[(lo+hi)//2]
    i = lo
    j = hi
    while True:
        while A[i] < pivot:
            i += 1
        while A[j] > pivot:
            j -= 1
        if i >= j:
            return j
        A[i], A[j] = A[j], A[i]


def quicksort(A, lo, hi):
    if lo < hi:
        p = partition(A, lo, hi)
        quicksort(A, lo, p)
        quicksort(A, p + 1, hi)

arr = [81, 4, 73, 1, 98, 69, 300, 14, 7, 420, 190, 8, 9]
quicksort(arr, 0, len(arr)-1)
print(arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM