【发布时间】:2021-03-01 01:45:43
【问题描述】:
所以我做了这个sorting排序方法,全部使用for循环。
我在白板上一遍又一遍地修改它,它看起来很完美,但是,当我实施它时,它总是给我错误的排序,但如果我颠倒if 条件,它会给我正确的答案,但在反过来,这没有意义!
public void insertionSort(){
for (int i = 1; i < items.length; i++){
for (int j = 0; j < i; j++){
if (items[i] < items[j]) {
int temp = items[i];
shift(items,j, i-1);
items[j] = temp;
}
}
}
}
private void shift(int[] array, int index1, int index2){
if (index1 == index2)
array[index1 + 1] = array[index1];
else{
for (int i = index2; i >= index1; i--)
array[i+1] = array[i];
}
}
【问题讨论】:
-
你的意思是哪个条件反过来可以工作
-
我在改变条件的两个方向上测试了这段代码 - 输入
int[] items = {2, 1, 3, 7, 9, 15, 10, 0};的排序工作正常,升序成功:[0, 1, 2, 3, 7, 9, 10, 15],降序也成功:[15, 10, 9, 7, 3, 2, 1, 0] -
我知道这不是你问的,但也许它与混乱有关......我觉得你在这里从零运行 j 到 i 很奇怪。它为您提供最佳情况二次运行时间。如果您从 i-1 开始运行 j 并在 items[j-1] > items[j] 时交换邻居,如果不是则中断,您将在排序输入上获得最佳情况线性运行时间,排序是稳定的,并且您不需要复杂的转变(交换邻居是微不足道的)。测试将是 if(items[j-1] > items[j]) {...} 这很简单
-
感谢您的输入,我在 Array 类中发现了问题,它只是将数组大小加倍,我的错误是我使用了 array.length 而不是 count。
-
@BWallDev,我的意思是 if 条件 if (items[i]
标签: java sorting data-structures insertion-sort