下面是我在python中实现快速排序的代码。但是我无法得到实施方面出错的地方。任何线索?
def quicksort(arr, size):
partition(arr, size)
def partition(arr, size):
if size <= 1:
return
left = 0
right = size - 1
pivot = arr[size/2]
while left < right:
while arr[left] < pivot:
left += 1
while arr[right] > pivot:
right -= 1
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
partition(arr, left)
partition(arr[left:], len(arr[left:]))
arr = [1,2,3,4,5,45,3,5,4,6]
quicksort(arr, len(arr))
答案 0 :(得分:1)
您正在对新切片进行排序:
partition(arr[left:], len(arr[left:]))
这些切片是新列表,而不是原始列表对象。您对arr
的原始值中显示的所有内容都不可见。
如果你想在原地进行排序,你需要传递开始和停止数组的哪个部分的值来排序,而不是传递切片:
def quicksort(arr):
partition(arr, 0, len(arr) - 1)
def partition(arr, start, stop):
if stop - start < 1:
return
left = start
right = stop
pivot = arr[start + ((stop - start) / 2)]
while left <= right:
while arr[left] < pivot:
left += 1
while arr[right] > pivot:
right -= 1
if left <= right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
partition(arr, start, right)
partition(arr, left, stop)
我做了一些调整,调整边界测试并使用元组赋值来交换这两个元素。
此版本正确排序:
>>> def quicksort(arr):
... partition(arr, 0, len(arr) - 1)
...
>>> def partition(arr, start, stop):
... if stop - start < 1:
... return
... left = start
... right = stop
... pivot = arr[start + ((stop - start) / 2)]
... while left <= right:
... while arr[left] < pivot:
... left += 1
... while arr[right] > pivot:
... right -= 1
... if left <= right:
... arr[left], arr[right] = arr[right], arr[left]
... left += 1
... right -= 1
... partition(arr, start, right)
... partition(arr, left, stop)
...
>>> arr = [1,2,3,4,5,45,3,5,4,6]
>>> quicksort(arr)
>>> arr
[1, 2, 3, 3, 4, 4, 5, 5, 6, 45]