简体   繁体   中英

Insertion sort array in java

So I made this sortion sort method, all using for loops.

I revised it on white board over and over, it looks perfect, however, when I implemented it, it keeps giving me wrong sort, but if I reversed the if condition, it will give me the right answer but in reverse, this doesn't make sense!

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];
    }
}

Thanks for the input, I discovered the problem in my Array class, it simply doubles the array size, my mistake was that I used the array.length instead of 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;
        }
   }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM