我正在尝试按照http://en.wikipedia.org/wiki/Quicksort
中的说明实现inplace快速排序下面是python代码,分区函数不能按预期工作。
def swap(array, index1, index2):
tmp = array[index1]
array[index1] = array[index2]
array[index2] = tmp
def partition(array, left, right, pivotIndex):
pivotValue = array[pivotIndex]
swap(array, pivotIndex, right)
storeIndex = left
for i in range(left, right - 1):
if array[i] < pivotValue:
swap(array, i, storeIndex)
storeIndex = storeIndex + 1
print array, i
swap(array, storeIndex, right)
return storeIndex
def quicksort(array, left ,right):
if right > left:
print left, right
pivotIndex = left
pivotNewIndex = partition(array, left, right, pivotIndex)
quicksort(array, left, pivotNewIndex - 1)
quicksort(array, pivotNewIndex + 1, right)
if __name__ == '__main__':
array = [3,7,8,5,2,1,9,5,4]
partition(array, 0, len(array) - 1, 3) # 5 is pivot
print array # expecting all the elements to the left of pivot value(5) will be lesser or equal.
答案 0 :(得分:3)
您需要至少修改2个:
def partition(array, left, right, pivotIndex):
pivotValue = array[pivotIndex]
swap(array, pivotIndex, right)
storeIndex = left
for i in range(left, right): # range doesn't include right element already
if array[i] <= pivotValue: # need to check for equality (not really necessary for the sorting routine)
swap(array, i, storeIndex)
storeIndex = storeIndex + 1
print array, i
swap(array, storeIndex, right)
return storeIndex
range(left, right)
会返回类似[left, left + 1, ..., right - 1]
的项目列表,因此无需生成包含range(left, right -1)
的列表,因为我们不仅会跳过该right - 2
的最后一个元素。 list(枢轴所在的位置),也是前一个(即partition
)。
如果预期在array[i] <= pivotValue
之后,枢轴左边的元素应该小于或相等,我们应该在数组遍历期间在比较中反映它({{1} })。
答案 1 :(得分:0)
使用较少的变量和干净的方法是不是更好的方法
#!的/ usr / bin中/ Python的
Array = [1,2,3,4,5,4,3,23,4,5,4,3,2,1,2,3,4,3,4,1,412,2,4]
def swap(a,i,j):
temp=a[i]
a[i]=a[j]
a[j]=temp
def partition(a, left, right):
pivotIndex=right
for i in range(left,right):
if a[i] > a[pivotIndex]:
swap(a,i,pivotIndex)
return pivotIndex
def quicksort(array , left,right):
if left<right:
pivotIndex=partition(array,left,right)
quicksort(array, left, pivotIndex-1)
quicksort(array, pivotIndex+1, right)
def main():
quicksort(Array, 0 , len(Array) -1)
print (Array )
main()