就地快速排序-python
我正在尝试在python中就地实现快速排序。我遵循了维基百科文章中的伪代码,但这并没有生成排序列表。有什么明显不正确的吗就地快速排序-python,python,Python,我正在尝试在python中就地实现快速排序。我遵循了维基百科文章中的伪代码,但这并没有生成排序列表。有什么明显不正确的吗 # Perform QuickSort in place def partition(arr,low,high): pivotIndex = random.randint(0,high) pivotValue = arr[pivotIndex] currentIndex = low t = arr[high] arr[high] =
# 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
#就地执行快速排序
def分区(arr、低、高):
pivotIndex=random.randint(0,高)
数据透视值=arr[数据透视索引]
当前索引=低
t=arr[高]
arr[高]=数据透视值
arr[数据透视索引]=t
对于范围内的i(低、高-1):
如果arr[i]
嗯,分区
函数的第一行显然是错误的:
pivotIndex = random.randint(0, high)
这显然应该是low
,而不是0
您的
范围
值可能已关闭。。。我认为您不需要从high
中减去1,而且在Python中,您不必使用时态变量来进行交换
而不是:
t = x
x = y
y = t
你可以做:
x, y = y, x
您是否记得导入随机的?此外,为了查看差异,数组必须是未排序的数组。如果元素的顺序已经正确,您如何找到差异
此外,通过将所有数组列为
arr
,可能会让人感到困惑。我注意到所有带有arr
的函数都使用arr
作为相应的参数。为什么不做一些区分它们的事情?“这不是生成一个排序列表”——它生成的是什么?实际问题是什么?