我正在尝试在python中实现quicksort.但是,我的代码没有正确排序(不完全).例如,在输入数组[5,3,4,2,7,6,1]上,我的代码输出[1,2,3,5,4,6,7].因此,最终结果介于4和5.我承认我在python上有点生疏,因为我一直在研究ML(在此之前它对python来说还是比较新的).我知道quicksort的其他python实现,以及关于python和quicksort的Stack Overflow上的其他类似问题,但我试图理解我自己写的这段代码有什么问题:
#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] …Run Code Online (Sandbox Code Playgroud)