Doubt with a test of a Java program

0

I have the following question about my Fundamentals of Programming class, the professor gives us the following code:

import java.util.Arrays; 

public class blablabla {

public static void main(String[] args) {
    int[] v1 = new int[] {9,6,2,1,4,0};
    int j;

    for (int i=1; i<v1.length; i++){

        int temp=v1[i];
        j=i-1;
        while (j>=0 && v1[j] > temp){
            v1[j+1] = v1[j];
            j--;
//                System.out.println("I es:" + i);
//                System.out.println("J es:" + j);
//                System.out.println("Temp es:" + temp);
        }
        v1[j+1]=temp;
//            System.out.println(Arrays.toString(v1));
    }

}
}

To this code you had to do a desktop test (a paper and pencil) to organize the array from least to greatest, so my question is, why does the program start with j = -1 when i = 1 and achieve Arrange the array correctly? Since the teacher when doing the test on a desktop sheet says that J = 0 when i = 1 and following the program line by line arranges the array correctly.

    
asked by Mateo Lopera 18.05.2018 в 14:41
source

1 answer

1

Since my explanation in the previous comment has been considered rather an answer, I detail the same below.

The value J is only -1 in the last step of the loop before leaving it because that is the condition to exit the loop, that is to say that the correct actions to be repeated are repeated whenever J > = 0 and apply the decrement of J until it "leaves" the action area.

In addition, of that detail, there is another can "confuse" when you learn. In this case it is the fact that the values are "printed" in each cycle after decrementing J (which prepares the next step of the loop). By this I mean that if you print the values after performing the operation on the array and before decrementing the J you will get a correct impression of the actions.

PS: Thanks again to @Leandro.

    
answered by 18.05.2018 в 17:18