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

Java MOOC习题7-3排序方法二次迭代后不交换问题排查

代码错误排查与修复

核心错误点

你的排序逻辑失效的根本原因是indexOfSmallestFrom方法没有正确实现需求:它完全忽略了传入的startIndex参数,始终从数组第0位开始查找最小值,而不是从startIndex指定的位置往后查找。这导致第一次交换后,后续循环无法定位到当前未排序区间的最小值,自然无法继续完成正确的交换排序。

修复后的代码

修复indexOfSmallestFrom方法

public static int indexOfSmallestFrom(int[] table, int startIndex) {
    // 初始最小值设为起始位置的值,索引为起始索引
    int minValue = table[startIndex];
    int minIdx = startIndex;

    // 从起始索引的下一位开始遍历到数组末尾
    for (int index = startIndex + 1 ; index < table.length; index++) {
        if (table[index] < minValue) {
            minValue = table[index];
            minIdx = index;
        }
    }

    return minIdx;
}

优化sort方法(可选但推荐)

原sort方法中两次调用indexOfSmallestFrom会重复计算,建议把结果存到变量中提升效率:

import java.util.Arrays;

public static void sort(int[] array) {
    for (int i = 0; i < array.length; i++) {
        int smallestIdx = indexOfSmallestFrom(array, i);
        if (array[i] > array[smallestIdx]) {
            swap(array, i, smallestIdx);
        }

        System.out.println(Arrays.toString(array));
    }
}

交换方法保持不变

public static void swap(int[] array, int index1, int index2) {
    int oldint1 = array[index1];
    array[index1] = array[index2];
    array[index2] = oldint1;
}

修复后逻辑说明

修复后的indexOfSmallestFrom会从startIndex开始,在未排序区间内查找最小值的索引。sort方法通过循环逐步将未排序区间的最小值交换到当前i的位置,最终实现整个数组的升序排序。

用测试数组{8, 3, 7, 9, 1, 2, 4}运行,会得到正确的排序过程输出:

[1, 3, 7, 9, 8, 2, 4]
[1, 2, 7, 9, 8, 3, 4]
[1, 2, 3, 9, 8, 7, 4]
[1, 2, 3, 4, 8, 7, 9]
[1, 2, 3, 4, 7, 8, 9]
[1, 2, 3, 4, 7, 8, 9]
[1, 2, 3, 4, 7, 8, 9]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:22:54