Issue
import java.util.Arrays;
import java.util.Scanner;
public class InsertionSort {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] arr = new int[s.nextInt()];
for (int i = 0; i < arr.length; i++) {
arr[i] = s.nextInt();
}
s.close();
new RunInsertionSort().insertionSort(arr);
System.out.println(Arrays.toString(arr));
}
}
class RunInsertionSort {
public void insertionSort(int[] arr) {
int i, j, temp;
for (i = 1; i < arr.length; i++) {
temp = arr[i];
j = i - 1;
while ((j >= 0) && (temp < arr[j])) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
}
If j>=0
is placed after the condition temp< arr[j]
, I'm getting the error as
5
5 4 3 2 1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5
at RunInsertionSort.insertionSort(InsertionSort.java:22)
at InsertionSort.main(InsertionSort.java:12)
But in C language this doesn't happen either I write j>=0 && temp < arr[i]
or temp<arr[i] && j>=0
.
1st Image Image of Error when j>=0 is placed after temp<arr[j]
2nd Image Image when j>=0 is placed before temp<arr[j]
Solution
No. Its called shortcircuit.
The order can affect your condition because if any of the conditions from left to right fails, it will mark the complete condition as false and doesn't evaluate any more conditions.
while ((j >= 0) && (temp < arr[j]))
So if j >= 0
is false, it will not evaluate temp < arr[j]
but if you interchange first it will evaluate temp < arr[j]
where arr[j]
can produce an ArrayIndexOutOfBoundsException in Java.
You can read more about shortCircuit.
In C, it may not give an exception; rather it may give you a garbage value.
Answered By - Pirate
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.