我已经尝试了两天,想弄清楚为什么我的快速排序函数返回的所有元素都被正确地排序,除了其中的两个。
以下是输入内容:
quicksort([0,7,3,11,23,87,999,1023,12,713,5,6,9])
输出
[0, 6, 3, 5, 7, 9, 11, 12, 23, 87, 713, 999, 1023]
你觉得这个函数哪里有问题?
def quicksort(array):
#Base case
if len(array) <= 1:
return array
#Choose pivot always at the left part and partition array around it
Pivot = partition(array,0,len(array));
#Add values for left and righ arrays
left = array[:Pivot]
right = array[Pivot+1:]
#Add recursive calls
left = quicksort(left)
right = quicksort(right)
#Append Pivot at the end of left array
left.append(array[Pivot])
return left+right
为了完整起见,我会添加分区函数,但我几乎确定问题不在那里。
def partition(array,left,right):
#If pivot is not on leftmost, swap to make it leftmost
Pivot = array[left]
i = left+1
for j in range(left+1,right):
if array[j] < Pivot:
#Swap array[j] and array[i]
array[j], array[i] = array[i], array[j]
i += 1;
#Swap pivot and A[i-1]
array[left], array[i-1] = array[i-1], array[left]
return left