[英]Quicksort not sorting the lower half
I am new to programming and trying to do Udacity's quicksort practice.我是编程新手,正在尝试进行 Udacity 的快速排序练习。 But my code doesn't quite do it.但我的代码并没有完全做到这一点。
Something might be wrong with how I assign low and high in the quicksort function, but I don't know how to fix it.我在快速排序 function 中分配低和高的方式可能有问题,但我不知道如何解决。
# 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)
Expected answer: [1, 3, 4, 6, 9, 14, 20, 21, 21, 25]预期答案:[1、3、4、6、9、14、20、21、21、25]
What I got: [1, 4, 3, 9, 6, 14, 20, 21, 21, 25]我得到了什么:[1、4、3、9、6、14、20、21、21、25]
To get the lower half of the array you need to do array[:pi]
not array[:pi-1]
.要获得数组的下半部分,您需要执行array[:pi]
而不是array[:pi-1]
。 The end index is exclusive.结束索引是独占的。 If you change the line to:如果将行更改为:
array[:pi] = quicksort(array[:pi])
your algorithm works: repl.it link您的算法有效: repl.it 链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.