让我们首先实现三个数的中值,所以是一个独立的函数。我们可以对三个元素的列表进行排序,然后返回第二个元素,如:
def median_of_three(a, b, c):
return sorted([a, b, c])[1]
现在是一个范围
low .. high
用
low
包括,和
high
不包括在内),我们应该确定哪些元素是我们应该构建三个中值的元素:
第一个要素:
L[low]
,
最后一个元素
L[high-1]
和
中间元素(如果有两个这样的元素,则取第一个)
L[(low+high-1)//2]
.
所以现在我们只需要将分区函数修补到:
def Partition(L, low, high, ascending = True):
print('Quicksort, Parameter L:')
print(L)
result = 0
pivot = median_of_three(L[low], L[(low+high-1)//2], L[high-1])
i = low + 1
for j in range(low + 1, high, 1):
result += 1
if (ascending and L[j] < pivot) or (not ascending and L[j] > pivot):
L[i], L[j] = L[j], L[i]
i += 1
L[low], L[i-1] =