固定取第一个,最坏和最好各多少次

👁️ 0 人浏览 💬 0 人评论 ❤️ 添加收藏

五个元素的全部 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)))
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论