我正在尝试在 python 中实现快速排序。但是,我的代码没有正确排序(不完全)。例如,在输入数组 [5,3,4,2,7,6,1] 上,我的代码输出 [1,2,3,5,4,6,7]。所以,最终结果插入了 4 和 5。我承认我对 python 有点生疏,因为我一直在研究 ML(并且在此之前对 python 相当陌生)。我知道快速排序的其他 python 实现,以及 Stack Overflow 上有关 python 和快速排序的其他类似问题,但我试图理解我自己编写的这段代码有什么问题:
#still broken 'quicksort'
def partition(array):
pivot = array[0]
i = 1
for j in range(i, len(array)):
if array[j] < array[i]:
temp = array[i]
array[i] = array[j]
array[j] = temp
i += 1
array[0] = array[i]
array[i] = pivot
return array[0:(i)], pivot, array[(i+1):(len(array))]
def quick_sort(array):
if len(array) <= 1: #if i change this to if len(array) == 1 i get an index out of bound error
return array
low, pivot, high = partition(array)
#quick_sort(low)
#quick_sort(high)
return quick_sort(low) + [pivot] + quick_sort(high)
array = [5,3,4,2,7,6,1]
print quick_sort(array)
# prints [1,2,3,5,4,6,7]