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

使用bubble sort排序int成绩数组时 同索引String课程数组出现值覆盖问题

问题原因

你在交换关联数组元素的步骤中,只完成了课程数组一半的交换逻辑:你将courses[i]覆盖为了courses[i+1]的值,但没有把原courses[i]的值存入courses[i+1]的位置,导致课程编号被批量覆盖,只有前两个未完全触发后续交换的条目保留了正确值。

修正后的代码

只需要调整交换逻辑,对课程数组也执行完整的交换操作即可:

// Using bottom to check the smaller list each time
int bottom = marks.length - 1;

// Once there are no more swaps, the list is sorted and it will leave
boolean hadSwap = true;
while (hadSwap) {
    // If there are no more swaps, it will leave
    hadSwap = false;
    
    // Checking ALL elements that could need to be moves
    for (int i = 0; i < bottom; i++) {
    
        // Checking two elements next to eachother to see if they need to be swapped
        if (marks[i] > marks[i + 1]) {
            hadSwap = true;
            // 交换分数数组
            int tempMark = marks[i];
            marks[i] = marks[i + 1];
            marks[i + 1] = tempMark;
            // 同步交换对应的课程数组
            String tempCourse = courses[i];
            courses[i] = courses[i+1];
            courses[i+1] = tempCourse;
        }
    }
    // The final item is in the right spot, shorten the list
    bottom--;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:36:07