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

如何修复Python实现的QuickSort代码,使其返回正确排序数组?

快速排序代码错误分析与修正

问题定位

你的代码核心问题是缩进错误,导致关键逻辑未正确执行,同时存在循环内未交换元素的逻辑漏洞:

  • 交换左右指针指向元素的语句被放在外层while (leftPointer < rightPointer)循环之外,循环结束后两指针位置重合,交换操作毫无意义,根本没完成分区的元素交换步骤。
  • 交换基准值(pivot)、递归调用、返回列表的语句缩进错误,导致代码块执行顺序混乱,部分逻辑跑到了else块之外,破坏了递归流程。

修正后的代码

class QuickSort:
    def quickSort(self, list, low, high):
        if low >= high:
            return list
        leftPointer = low
        rightPointer = high
        pivot = list[high]
        while leftPointer < rightPointer:
            # 左指针右移,找到大于等于pivot的元素
            while leftPointer < rightPointer and list[leftPointer] < pivot:
                leftPointer += 1
            # 右指针左移,找到小于等于pivot的元素
            while leftPointer < rightPointer and list[rightPointer] > pivot:
                rightPointer -= 1
            # 交换左右指针指向的元素,这一步必须在循环内部
            list[leftPointer], list[rightPointer] = list[rightPointer], list[leftPointer]
        # 将基准值放到正确的位置(此时leftPointer和rightPointer重合)
        list[high], list[leftPointer] = list[leftPointer], list[high]
        # 递归排序左右子数组
        self.quickSort(list, low, leftPointer - 1)
        self.quickSort(list, leftPointer + 1, high)
        return list


list = [50, 49, 19, 4, 9]
quick = QuickSort()
print(quick.quickSort(list, 0, len(list) - 1))

关键修正说明

  1. 把交换左右指针元素的语句移到外层while循环内部,确保每次找到不符合条件的元素后立即交换,完成分区的核心步骤。
  2. 统一缩进格式,去掉多余的else分支(if分支已返回,后续代码自然属于逻辑上的else分支),保证代码块执行顺序正确。
  3. 修正递归终止条件的返回值,当low >= high时返回原列表,避免上层递归接收None。

内容的提问来源于stack exchange,提问作者Jack Booth

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 20:00:11