[英]In-place quicksort - python
I'm trying to implement quicksort in python in-place. 我正在尝试在python中实现quicksort。 I followed the pseudocode from the wikipedia article here, but this is not producing a sorted list. 我遵循了Wikipedia文章中的伪代码,但这未生成排序列表。 Does anything seem glaringly incorrect? 看起来有什么不对劲吗?
# 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
Well, the first line of the partition
function is clearly wrong: 好吧, partition
功能的第一行显然是错误的:
pivotIndex = random.randint(0, high)
This should obviously be low
instead of 0
. 显然这应该是low
而不是0
。
Your range
values might be off... I don't think you need to subtract 1 from high
. 您的range
值可能已关闭...我认为您不需要从high
减去1。
Also, in Python you don't have to use a temporal variable to do an exchange. 另外,在Python中,您不必使用时间变量来进行交换。
Instead of: 代替:
t = x
x = y
y = t
You can do: 你可以做:
x, y = y, x
Did you remember to import random
? 您还记得import random
吗? Also, in order to see the difference, your array must be an unsorted one. 同样,为了看到差异,您的数组必须是未排序的数组。 If the elements are already in the correct order, how can you find the difference? 如果元素已经按照正确的顺序排列,您如何找到差异?
Also, by listing all the arrays as arr
, it can get confusing. 另外,通过将所有数组列为arr
,可能会造成混乱。 I noticed that all functions with arr
in them are using arr
as the corresponding parameter. 我注意到所有带有arr
函数都使用arr
作为相应的参数。 Why not do something do distinguish them? 为什么不区分某些东西?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.