【发布时间】:2016-02-22 13:34:30
【问题描述】:
我试图实现this video 和this document 中讨论的算法。
我的快速排序代码,它依赖于选择 数组中的中间元素 作为枢轴(见下文),而不是上面文档作者使用的方法,它使用 数组中的第一个元素作为shown here in the video的主元。
显然,我的代码不起作用(最终会超出递归限制)。我想知道这是否是因为我的代码中有一些愚蠢的错误,或者只要我从中间选择支点,它就无法正常工作。
def partition(a, start, end):
# I pick the pivot as the middle item in the array
# but the algorithm shown in the video seems to
# pick the first element in the array as pivot
piv = (start + end) // 2
pivotVal = a[piv]
left = start
right = end
while left <= right:
while a[left] < pivotVal:
left += 1
while a[right] > pivotVal:
right -= 1
if left <= right:
temp = a[left]
a[left] = a[right]
a[right] = temp
left += 1
right -= 1
return left
def quicksort(a, start, end, k):
if start < end:
piv = partition(a, start, end)
if piv == (k - 1):
print("Found kth smallest: " + piv)
return a[piv]
elif piv > (k - 1):
return quicksort(a, start, piv, k)
else:
return quicksort(a, piv + 1, end, k)
myList = [54, 26, 93, 17, 77, 31, 44, 55, 20]
quicksort(myList, 0, len(myList) - 1, 3)
print(myList)
【问题讨论】:
-
你检查过快速选择算法吗?
-
您正在使用包含数组边界。你让这变得不必要的困难。使用 [start, end) 几乎可以更优雅地描述每个算法。
-
你在
partition函数中混合了a和arr。 -
@FaizHalde,是的。我做到了。我只是想用不同的方法尝试它,因为使用快速排序似乎更方便我记住这种方法。
-
@thefourtheye 感谢您指出这一点。我修正了错字。但是这个错字不是代码不起作用的问题。
标签: python algorithm quicksort