简体   繁体   English

快速排序算法中的中间分区 Python

[英]Middle partition in quicksort algorithm Python

I'm trying to implement quicksort algorithm which uses middle partitioning method.我正在尝试实现使用中间分区方法的快速排序算法。 below is my code:下面是我的代码:

def middlepartition(A, p, r):
    pvi = (p + r) // 2
    pv = A[pvi]

    while p < r:
        while p < len(A) and A[p] <= pv:
            p += 1
        while A[r] > pv:
            r -= 1
        if p < r:
            A[p], A[r] = A[r], A[p]
    A[r], A[pvi] = A[pvi], A[r]

    return r


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


A = [0, 1, 5, 23, 0, 2, 5, 56, 79, 3, 65]
quicksort(A, 0, len(A)-1)
print(A)

but somehow the code doesn't work fine and I'm really confused.但不知何故,代码不能正常工作,我真的很困惑。 the following is the output:以下是output:

[0, 1, 2, 5, 23, 0, 3, 5, 56, 65, 79]

I seriously cant find the mistake...我真的找不到错误...

This is your mistake:这是你的错误:

A[r], A[pvi] = A[pvi], A[r]

(or at least a mistake - there could be other issues). (或者至少是一个错误——可能还有其他问题)。

This bit of code occurs in variants of QuickSort that initially move (swap) the pivot element to the end of the array and then exclude that slot from the body of the partitioning loop.这段代码出现在 QuickSort 的变体中,最初将 pivot 元素移动(交换)到数组的末尾,然后从分区循环的主体中排除该插槽。 Once the partitioning loop is done, the initial pivot element is moved into place at the point where the pivot index has emerged.分区循环完成后,初始 pivot 元素将移动到出现 pivot 索引的位置。

That's not what you're doing here, though - when control reaches the above statement the pvi index points to a random element, so the swap messes you up.不过,这不是你在这里做的——当控制到达上述语句时, pvi索引指向一个随机元素,所以交换会把你弄乱。 Just get rid of it - the partitioning loop will have already put the pivot element in the right place at that point.只需摆脱它 - 分区循环已经将 pivot 元素放在正确的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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