固定取第一个,最坏和最好各多少次
五个元素的全部 120 种排列,快排总是拿第一个当 pivot,比较次数的最大值和最小值:
from itertools import permutations
def qs_cmp(a):
"""总是拿第一个当 pivot 的快排,返回比较次数"""
c = 0
def go(x):
nonlocal c
if len(x) <= 1:
return
p = x[0]
c += len(x) - 1
go([y for y in x[1:] if y < p])
go([y for y in x[1:] if y >= p])
go(list(a))
return c
P = list(permutations(range(5)))
print(str(max(qs_cmp(p) for p in P)) + "/" + str(min(qs_cmp(p) for p in P)))
全部评论