这两个 Quicksort 分区函数有什么区别?
What's the difference between these two Quicksort partition functions?
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 编写快速排序,但我不明白 Python 中出了什么问题。
PartitionDemo 有
while start<end and a[start]<x :
Partition2 的位置
while low < high and a[high] < key:
看来你的应该是
while start<end and a[end]<x :
将第二个开头替换为结尾
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 编写快速排序,但我不明白 Python 中出了什么问题。
PartitionDemo 有
while start<end and a[start]<x :
Partition2 的位置
while low < high and a[high] < key:
看来你的应该是
while start<end and a[end]<x :
将第二个开头替换为结尾