[英]Quick Sort Algorithm using python
我将第一个元素作为起始和 pivot 值。
当 pivot 小于结束值时,递增开始 position。
当 pivot 大于结束值时,递减结束 position。
此外,每次通过完成时交换开始和结束 position。
如果开始 position 穿过末端 position 那么我将交换 pivot 和末端元素。
def partition(arr, lb, ub):
pivot = arr[lb]
start = lb
print('start', start)
end = ub
print('end', end)
while start <= end:
while arr[start] <= pivot:
start += 1
while arr[end] >= pivot:
end -= 1
if start <= end:
arr[start], arr[end] = arr[end], arr[start]
else:
arr[end], arr[lb] = arr[lb], arr[end]
return end
def quickSort(arr, lb, ub):
if lb >= ub:
return 0
loc = partition(arr, lb, ub)
quickSort(arr, lb, loc-1)
quickSort(arr, loc+1, ub)
arr = [10, 4, 7, 3, 8, 6, 9, 1, 5, 2]
n = len(arr)
print(n)
quickSort(arr, 0, len(arr) -1)
print ("Sorted array is:")
for i in range(n):
print("%d" % arr[i])
我收到以下错误:IndexError
---> quickSort(arr, 0, len(arr) -1)
Error in partition(arr, lb, ub)
---> while arr[start] <= pivot:
IndexError: list index out of range
有人可以告诉这段代码有什么问题吗?
这是错误的直接原因:
while arr[start] <= pivot:
start += 1
while arr[end] >= pivot:
end -= 1
您不检查start
是否不大于ub
(以及end
是否不小于lb
)。 这是你应该做的:
while start < ub and arr[start] <= pivot:
start += 1
while end > lb and arr[end] >= pivot:
end -= 1
然而,还有一点不对:
while start <= end:
应该
while start < end:
因为对于弱不等式,循环永远不会结束 - 它到达start == end
的 state 并在那里无限循环。 这里的不等式:
if start <= end:
也应该是一个强大的,否则对于start == end
你将arr[end]
与arr[start]
(即它本身)而不是arr[lb]
(即枢轴)交换。
最后,这里发布的代码格式很糟糕,所以我冒昧地修复了它。
不确定您是否还没有解决方案,但这里有一个修改后的分区 function。
def partition(arr, lb, ub):
pivot = arr[lb]
start = lb + 1
print('start', start)
end = ub
print('end', end)
while start <= end:
while start <= end and arr[start] <= pivot:
start += 1
while end >= start and arr[end] > pivot:
end -= 1
if start < end:
arr[start], arr[end] = arr[end], arr[start]
if start >= end:
start -= 1
arr[start], arr[lb] = arr[lb], arr[start]
return start
您需要检查start
的增量是否不超过end
,如下所示,
while arr[start] <= pivot:
if start<end:
start += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.