When I replaced j+1 with ++j it got stuck over there with an infinite loop neither incrementing nor decrementing public class InsertionSort {
public static void main(String[] args) {
int[] arr= {5,7,6,4,8,9,3,1,2};
int n = arr.length;
for(int i = 1 ; i < n ; i++) {
int j = i-1;
int key = arr[i];
while(j>=0&&key<arr[j]) {
arr[j+1]=arr[j--]; // ***Working Fine***
}
arr[++j]=key;
}
for (int i : arr) {
System.out.print(i+" ");
}
}
}
Getting stucked in the below code
public class InsertionSort {
public static void main(String[] args) {
int[] arr= {5,7,6,4,8,9,3,1,2};
int n = arr.length;
for(int i = 1 ; i < n ; i++) {
int j = i-1;
int key = arr[i];
while(j>=0&&key<arr[j]) {
arr[++j]=arr[j--];// ***Stucked***
}
arr[++j]=key;
}
for (int i : arr) {
System.out.print(i+" ");
}
}
}
This is meant to be stuck infinitely. In the first example of j+1, the value of j is not incremented when you do j+1.
while(j>=0&&key<arr[j]) {
arr[j+1]=arr[j--]; // value of J is not incremented, it's actually decremented by j--.
}
In the second example of ++j, there are two operations being performed.
Operation 1:
arr[++j] // This operation increments the value of j
Operation 2:
arr[j--] // This operation decrements the value of j
In the same line, you are incrementing and decrementing the value of j. Hence the value of j is never 0 and it's stuck in an infinite loop. Hope this clarifies the issue.