Java选择排序数组数值正确但输出元素原始索引部分错误求助
问题排查与修复方案
根因分析
你当前的实现直接在原始数值数组上做交换操作,排序过程中数组元素的位置已经被打乱,你记录的maxId是交换过程中临时数组的下标,并非初始状态下的原始数组下标,因此只有部分索引输出符合预期。
修复方案
单独维护一个和数值数组一一对应的索引数组,每次交换数值元素时同步交换索引数组的对应元素,保证索引数组中存储的永远是对应位置数值的原始下标。
修改后代码如下:
public static void sortNumbers(double[] averageNotes) { // 初始化索引数组,存储每个位置对应的原始下标 int[] indices = new int[averageNotes.length]; for (int i = 0; i < averageNotes.length; i++) { indices[i] = i; } for (int i = 0; i < averageNotes.length; i++) { double max = averageNotes[i]; int maxId = i; for (int j = i+1; j < averageNotes.length; j++) { if (averageNotes[j] > max) { max = averageNotes[j]; maxId = j; } } // 同步交换数值数组和索引数组的元素 double tempNote = averageNotes[i]; averageNotes[i] = averageNotes[maxId]; averageNotes[maxId] = tempNote; int tempIndex = indices[i]; indices[i] = indices[maxId]; indices[maxId] = tempIndex; // 输出对应位置的原始索引 System.out.println(averageNotes[i] + " (" + indices[i] + ")"); } }
内容的提问来源于stack exchange,提问作者user15840856
相关产品推荐
相关产品推荐

