这两个Quicksort分区函数有什么区别?

时间:2016-07-11 16:53:06

标签: python quicksort

def PartitionDemo(a,p,r):
    x=a[p]
    start=p
    end=r
    while start<end :
        while start<end and a[end]>=x :
            end-=1
        while start<end and a[start]<x :
            a[start]=a[end]
            start+=1
            a[end]=a[start]
    a[start]=x
    return start

def Partition2(a,low,high):
    key = a[low]
    while low < high:
        while low < high and a[high] >= key:
            high -= 1
        while low < high and a[high] < key:
            a[low] = a[high]
            low += 1
            a[high] = a[low]
    a[low] = key
    return low

PartitionDemo我自己写了,Partition2我从互联网上复制了它。但是,PartitionDemo无法正常运行;它不能跳出循环。我认为他们使用相同的逻辑,但Partition2效果很好。

我尝试用C ++,Java和Python编写Quicksort,但我不明白Python中出了什么问题。

1 个答案:

答案 0 :(得分:1)

PartitionDemo有

while start<end and a[start]<x :

Partition2有

while low < high and a[high] < key:

所以看起来你应该

while start<end and a[end]<x :

用结束

替换第二个开头
相关问题