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

选择排序算法数组排序异常:负数数组无法正确排序

问题分析与修复

你的选择排序代码在处理含负数的数组时排序失败,核心问题出在getMaxIndex函数的遍历逻辑上:

  • 循环终止条件错误:原代码中for (int i = 0; i < last; i++)会漏掉索引为last的元素,导致无法在完整的[0, last]区间内找到最大值。
  • 循环起始值逻辑冗余:函数接收了start参数却未使用,始终从i=0开始遍历,虽当前调用场景下start固定为0,但逻辑上存在缺陷。

修正后的代码

只需修改getMaxIndex函数,确保遍历区间内的所有元素:

static void selection(int[] array) {
    for (int i = 0; i < array.length; i++) {
        int last = array.length - i - 1;
        int max= getMaxIndex(array, 0, last);
        swap(array, max, last);
    }
}

static void swap(int[] arr, int first, int second) {
    int temp = arr[first];
    arr[first] = arr[second];
    arr[second] = temp;
}

static int getMaxIndex(int[] arr, int start, int last) {
    int max = start;
    // 从start遍历到last(包含last),覆盖完整区间
    for (int i = start; i <= last; i++) {
        if (arr[max] < arr[i]) {
            max = i;
        }
    }
    return max;
}

修复说明

修正后的getMaxIndex函数会从start开始,遍历到last(包含该索引),确保在指定区间内找到真正的最大值索引。无论数组元素是正数还是负数,都能完成正确的选择排序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:40:37