首页 > 解决方案 > Java插入排序:“相同”的变量得到不同的结果

问题描述

我正在使用 Java 进行插入排序。例如,如果我有一个整数数组 {8,7,6,5,4,3,2,1},

这会给我错误的结果:7,6,5,4,3,2,1,8图片

public static int[] insertionSort(int[] list) {
    int[] insertionList = list.clone();
    for(int i = 1; i < insertionList.length; i++) {
        int temp = insertionList[i];
        int j = i - 1;
        while(j >= 0 && insertionList[j] > insertionList[i]) {
            insertionList[j + 1] = insertionList[j];
            j--;
        }
        insertionList[j + 1] = temp;
    }
    return insertionList;
}

这会给我想要的结果:1,2,3,4,5,6,7,8图片

public static int[] insertionSort(int[] list) {
    int[] insertionList = list.clone();
    for(int i = 1; i < insertionList.length; i++) {
        int temp = insertionList[i];
        int j = i - 1;
        while(j >= 0 && insertionList[j] > temp) {
            insertionList[j + 1] = insertionList[j];
            j--;
        }
        insertionList[j + 1] = temp;
    }
    return insertionList;
}

insertionList[i]只是想知道和之间有什么不同temp。我写了两条println语句来测试这些,但它们也显示相同的数字。

谢谢!!!!!

标签: javaalgorithm

解决方案


不同之处在于“insertionList”在 while 循环内被修改。当您将 temp 变量设置为 'insertionList[i]' 时, temp 的值在整个 while 循环中保持不变。


推荐阅读