我试图在python中实现quicksort。我遵循维基百科文章中的伪代码,但这不是产生排序列表。有什么看似明显不正确吗?
# Perform QuickSort in place
def partition(arr,low,high):
pivotIndex = random.randint(0,high)
pivotValue = arr[pivotIndex]
currentIndex = low
t = arr[high]
arr[high] = pivotValue
arr[pivotIndex] = t
for i in range(low,high-1):
if arr[i] < pivotValue:
t = arr[i]
arr[i] = arr[currentIndex]
arr[currentIndex] = t
currentIndex += 1
t = arr[currentIndex]
arr[currentIndex] = arr[high]
arr[high] = t
return currentIndex
def quickSort(arr,low,high):
# pick partition
if low < high:
part = partition(arr,low,high)
quickSort(arr,low,part-1)
quickSort(arr,part+1,high)
arr = [1,3,6,7,9,10]
quickSort(arr,0,len(arr)-1)
print arr
答案 0 :(得分:2)
嗯,partition
函数的第一行显然是错误的:
pivotIndex = random.randint(0, high)
这显然应该是low
而不是0
。
您的range
值可能已关闭...我认为您不需要从high
中减去1。
答案 1 :(得分:0)
此外,在Python中,您不必使用时态变量进行交换。
而不是:
t = x
x = y
y = t
你可以这样做:
x, y = y, x
答案 2 :(得分:0)
你还记得import random
吗?此外,为了查看差异,您的数组必须是未排序的数组。如果元素的排序正确,您如何找到差异?
此外,通过将所有数组列为arr
,它可能会让人感到困惑。我注意到其中包含arr
的所有函数都使用arr
作为相应的参数。为什么不做一些区别对待呢?