java - 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
语句来测试这些,但它们也显示相同的数字。
谢谢!!!!!
解决方案
不同之处在于“insertionList”在 while 循环内被修改。当您将 temp 变量设置为 'insertionList[i]' 时, temp 的值在整个 while 循环中保持不变。
推荐阅读
- debugging - 当 Visual Studio 调试器打开时,一些 Web Api 端点非常慢
- php - 在总小时列中的 mysql 中显示“小时”
- android - Android微调器下拉图标隐藏在背景图像下
- r - 将变量从因子更改为数字会更改顺序
- nginx - 如何命令 Nginx 停止重定向到其 404 页面?
- python - question_number = int(sys.argv[1]) IndexError: 列表索引超出范围
- vba - 如何以相同的格式将文本从一个文档复制到另一个文档?
- sql-server - SQL Server Management Studio:LocalDb 不显示
- python - ROC曲线绘制
- react-native - 在本机反应中未授予位置权限