Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a difference between two similar implementations of a 'for' loop?

Tags:

java

I'm trying to write an insertion sort method, and I have managed to finish it, but I don't understand why my first version cannot work correctly.

Here's my first attempt:

public static void insertionSort(int[] list) {
    for (int i = 1; i < list.length; i++) {
        int current = list[i];
        for (int k = i - 1; k >= 0 && current < list[k]; k--) {
            list[i] = list[k];
            list[k] = current;
        }
    }
}

public static void main(String[] args) {
    int[] list = {8, 22, 90, 10};
    insertionSort(list);
}

My output for the above code is: 8, 10, 10, 22

But the answer would be correct if the inside for-loop, at line 5, is changed from: list[i] = list[k]; to: list[k + 1] = list[k];

To my understanding, k + 1 is equal to i, but it must be different in loop counting and I can't figure out how. I have tried many sets of input, and only values that lie between the range of the 2 first indexes (in this case 8 and 22) would be incorrect.

like image 241
nglu Avatar asked Jan 02 '19 09:01

nglu


People also ask

Why we use loop differentiate among different loops?

The 'for' loop used only when we already knew the number of iterations. The 'while' loop used only when the number of iteration are not exactly known. If the condition is not put up in 'for' loop, then loop iterates infinite times. If the condition is not put up in 'while' loop, it provides compilation error.

What are the main differences and similarities between a while loop and a for loop?

The major difference between for loop and while loop is that for loop is used when the number of iterations is known whereas, in the while loop, execution is done until the statement in the program is proved wrong.

How are loops similar to if statements How are they different?

Meaning an if statement gives you once the possibility to do something or not (or something else). Whereas a while loop does things as long as the condition is true.

What are the differences between the two types of iteration?

The major difference between them is that for loops are easier to read when iterating over a collection of something, and while loops are easier to read when a specific condition or boolean flag is being evaluated.


1 Answers

k + 1 is equal to i, but only in the first iteration of the inner for loop. int k = i - 1 is only run once per iteration of the outer for loop.

In the second iteration of the inner for loop, k is decremented but i is not. Therefore, k + 1 and i are not interchangeable inside the inner for loop.

// second iteration of the outer for loop, second iteration of the inner for loop:
list[i] = list[k]; // means "list[2] = list[0]
// whereas
list[k + 1] = list[k]; // means "list[1] = list[0]"
like image 80
Sweeper Avatar answered Nov 10 '22 10:11

Sweeper