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

JavaScript快速排序代码输出不符合预期,请求错误分析与解决方案

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

核心错误

  • 循环起始索引错误:pivot函数中for循环的起始值i=1是硬编码,应该改为start + 1。当递归处理数组的子区间时(比如右半部分),start参数不为0,硬编码1会导致跳过子区间的起始元素,甚至访问不属于当前子区间的位置。
  • 循环终止条件错误:循环条件i < end会遗漏索引为end的元素,正确的条件应为i <= end,确保当前子区间的所有元素都被遍历比较。

修复后的完整代码

const arr = [5, 2, 4, 2, 1, 9, 5, 8, 7, 4];

const quickSort = (arr, left = 0, right = arr.length - 1) => {
    if (left < right) {
        let pivotIndex = pivot(arr, left, right)
        quickSort(arr, left, pivotIndex - 1);
        quickSort(arr, pivotIndex + 1, right);
    }
    return arr;
}

const pivot = (arr, start = 0, end = arr.length - 1) => {
    const swap = (arr, i, j) => {
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }

    let pivot = arr[start];
    let swapIndex = start;

    // 修正循环的起始与终止条件
    for (let i = start + 1; i <= end; i++) {
        if (arr[i] < pivot) {
            swapIndex++;
            swap(arr, swapIndex, i);
        }
    }
    swap(arr, start, swapIndex)
    return swapIndex
}

console.log(quickSort(arr)); // 输出: [1, 2, 2, 4, 4, 5, 5, 7, 8, 9]

修复逻辑说明

修正后的pivot函数会正确遍历当前子区间的所有元素,将小于基准值的元素逐步交换到基准值左侧,最终返回基准值的正确索引。递归调用时,左右子区间的划分也会基于正确的基准索引,从而完成整个数组的升序排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 17:15:36