【发布时间】:2019-03-24 16:44:45
【问题描述】:
我需要实现插入排序,但我必须使用另一个名为 temp 的数组。在这个数组中,必须将起始数组的值复制到正确的位置
我尝试通过一些我认为可以完成任务的修改来实现插入排序算法
public static void insertionSort(int[] a) {
int[] temp = new int[a.length];
for(int indice = 0; indice < a.length; indice++) {
int key = a[indice];
int j = indice - 1;
while(j>=0 && a[j] > key) {
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp[j+1];
}
}
我尝试将它与具有以下数字的数组一起使用:5、1、4、14、21、144、3 但是打印出来的是 0 0 0 0 0 0 0
【问题讨论】:
-
你用
temp做什么? -
我使用 temp 作为第二个数组,以正确的顺序将值放入其中
-
不,你没有。这就是我问这个问题的原因,让你检查你的代码。
-
如果要插入排序,实现插入排序。请参阅 Wikipedia、en.wikipedia.org/wiki/Insertion_sort 或其他任何地方的算法。
int[] temp不存在。 -
或者,如果您想返回输入数组的有序副本:1) 确保在任何地方都使用
temp,除非您在开头创建副本 2) 也返回它 (返回void不会完成这项工作)。
标签: java insertion-sort