You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何统计quicksort基本操作次数并正确返回count变量

问题原因
  • Python中整数属于不可变对象,你传入递归函数的count只是值拷贝,子函数内部对count的修改不会作用于上层函数的变量
  • 现有函数仅返回排序后的列表,没有将累计的操作次数同步返回,无法统计递归各层的总操作数
  • 额外注意:不要用list作为变量名,会覆盖Python内置的list类型,容易引发未知错误
修复后的代码
def quickSort(arr, count):
    n = len(arr)
    less = []
    greater = []

    if n <= 1:
        # 边界场景:数组长度<=1无需排序,返回原数组和当前累计计数
        return arr, count

    pivot = arr[0]
    # 统计当前层级的比较操作次数
    current_level_count = 0
    for x in arr[1:]:
        if x <= pivot:
            less.append(x)
        else:
            greater.append(x)
        current_level_count += 1
    
    # 递归处理左右子区间,拿到排序结果和子区间累计操作次数
    sorted_less, count_less = quickSort(less, count)
    sorted_greater, count_greater = quickSort(greater, count)

    # 总操作次数 = 左子区间次数 + 当前层级次数 + 右子区间次数
    total_count = count_less + current_level_count + count_greater
    return sorted_less + [pivot] + sorted_greater, total_count
调用示例
test_arr = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_result, total_ops = quickSort(test_arr, 0)
print("排序结果:", sorted_result)
print("基本操作总次数:", total_ops)

内容的提问来源于stack exchange,提问作者나승주

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 18:00:04