快速排序不对下半部分进行排序
Quicksort not sorting the lower half
我是编程新手,正在尝试进行 Udacity 的快速排序练习。但是我的代码并没有完全做到这一点。
我在快速排序函数中分配 low 和 high 的方式可能有问题,但我不知道如何解决它。
# this returns a sorted array
def quicksort(array):
low = 0
high = len(array) - 1
if low >= high:
return array
pi = partition(array, low, high)
array[:pi-1] = quicksort(array[:pi-1])
array[pi+1:] = quicksort(array[pi+1:])
return array
# this places the pivot in the right position in the array.
# all elements smaller than the pivot are moved to the left of it.
def partition(array, low, high):
border = low
pivot = array[high]
for i in range(low, high):
if array[i] <= pivot:
array[border], array[i] = array[i], array[border]
border += 1
array[border], array[high] = array[high], array[border]
return border
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)
预期答案:[1, 3, 4, 6, 9, 14, 20, 21, 21, 25]
我得到的是:[1, 4, 3, 9, 6, 14, 20, 21, 21, 25]
要获取数组的下半部分,您需要执行 array[:pi]
而不是 array[:pi-1]
。结束索引是独占的。如果将行更改为:
array[:pi] = quicksort(array[:pi])
你的算法有效:repl.it link
我是编程新手,正在尝试进行 Udacity 的快速排序练习。但是我的代码并没有完全做到这一点。
我在快速排序函数中分配 low 和 high 的方式可能有问题,但我不知道如何解决它。
# this returns a sorted array
def quicksort(array):
low = 0
high = len(array) - 1
if low >= high:
return array
pi = partition(array, low, high)
array[:pi-1] = quicksort(array[:pi-1])
array[pi+1:] = quicksort(array[pi+1:])
return array
# this places the pivot in the right position in the array.
# all elements smaller than the pivot are moved to the left of it.
def partition(array, low, high):
border = low
pivot = array[high]
for i in range(low, high):
if array[i] <= pivot:
array[border], array[i] = array[i], array[border]
border += 1
array[border], array[high] = array[high], array[border]
return border
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print quicksort(test)
预期答案:[1, 3, 4, 6, 9, 14, 20, 21, 21, 25]
我得到的是:[1, 4, 3, 9, 6, 14, 20, 21, 21, 25]
要获取数组的下半部分,您需要执行 array[:pi]
而不是 array[:pi-1]
。结束索引是独占的。如果将行更改为:
array[:pi] = quicksort(array[:pi])
你的算法有效:repl.it link