java中的排序插入排序数组

yv5phkfx  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(257)

所以我做了这个分类方法,全部使用 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];
    }
}
lmyy7pcs

lmyy7pcs1#

感谢您的输入,我在array类中发现了问题,它只是将数组大小增加了一倍,我的错误是使用了array.length而不是count。

public void insertionSort(){
for (int i = 1; i < count; 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;
        }
   }
}

}

相关问题