You need to enable JavaScript to run this app. 调试Java实现的简单快速排序(quicksort)输出不符合预期问题
优惠活动
大模型
产品
解决方案
定价
更多

调试Java实现的简单快速排序(quicksort)输出不符合预期问题

问题定位

你实现的快速排序存在两处逻辑错误,直接导致最终排序不完整:

  • 右半分区的递归判断条件写反:代码中用index > high判断是否需要递归排序右区间,这个条件永远无法成立。
    因为partition方法返回的是左右指针交叉时的左指针位置,最大取值不会超过high + 1,不存在大于high的可能,这就导致数组右半部分的元素从来没有进入过递归排序流程,最终出现22和28顺序颠倒的问题。
  • 缺少基础的递归终止保护:方法入口没有判断当low >= high(对应子数组长度为0或1,本身已有序)的场景,在边界计算时会触发不必要的partition调用,甚至可能出现数组越界。
修正后可正常运行的代码
public class Quicksort2 {
    public static void main(String[] args) {
        int[] arr = {22, 9, 8, 45, 28, 7, 1};
        quicksort(arr, 0, arr.length - 1);
        for (int i = 0; i < arr.length; i++)
            System.out.print(arr[i] + " ");
    }

    static void quicksort(int[] arr, int low, int high) {
        // 增加终止判断:子区间长度<=1时直接返回,无需排序
        if (low >= high) {
            return;
        }
        int index = partition(arr, low, high);

        // 递归排序左区间:区间长度大于1时触发
        if (low < index - 1) {
            quicksort(arr, low, index - 1);
        }
        // 修正右区间判断:分界点未到右边界时,递归排序该区间
        if (index < high) {
            quicksort(arr, index, high);
        }
    }

    static int partition(int[] arr, int low, int high) {
        int pivot = arr[(low + high) / 2];
        int i = low;
        int j = high;
        while (i <= j) {
            while (arr[i] < pivot) i++;
            while (arr[j] > pivot) j--;

            if (i <= j) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
            }
        }
        return i;
    }
}
运行结果

修正后代码会输出符合预期的排序结果:

1 7 8 9 22 28 45

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 06:45:06