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

Python编写快速排序算法运行后无法得到正确输出问题求助

快速排序代码问题修正

你的代码存在以下几处错误:

  • 函数缩进错误:quickSort函数目前被缩进在partition函数内部,属于局部函数,全局作用域无法调用,需要将quickSort的缩进调整到和partition同级。
  • 分区函数边界异常:内层遍历的while循环没有加索引边界限制,当基准值为当前区间最大值时,i会持续递增超出数组下标范围,触发索引越界。同时外层循环结束时天然满足j <= i,额外的if i > j判断属于多余逻辑,可直接删除。
  • 排序调用参数错误:quickSort的后两个入参是数组待排序区间的左右索引下标,不是数组的首尾元素值,你当前调用时传入的a[0]和a[l-1]是元素值,应修改为0和len(a)-1。

修正后完整代码

def partition(arr, low, high):
    pivot = arr[low]
    i = low
    j = high

    while i < j:
        # 新增索引边界判断防止越界
        while i <= high and arr[i] <= pivot: 
            i = i + 1
        while j >= low and arr[j] > pivot: 
            j = j - 1
        if i < j:
            arr[i], arr[j] = arr[j], arr[i]
    # 交换基准值到排序后的正确位置
    arr[j], arr[low] = arr[low], arr[j]
    return j

# 调整缩进为全局函数
def quickSort(arr, low, high):
    if low < high:
        pivot = partition(arr, low, high)
        quickSort(arr, low, pivot-1)
        quickSort(arr, pivot+1, high)


a = []
n = int(input("Enter the number of elements : "))
print("Enter the elements now")
for i in range(0, n):
    element = int(input())
    a.append(element)

print("Given array :", a)
l = len(a)
# 传入正确的索引参数
quickSort(a, 0, l-1)
print("Sorted array is :", a)

内容的提问来源于stack exchange,提问作者Mayur Panchal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:57:05