0
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]

8
  • The answer is no May 27, 2022 at 5:14
  • Also, works without an error for me 5 5 4 3 2 1 [1, 2, 3, 4, 5] May 27, 2022 at 5:16
  • 2
    C doesn't do index bounds checks. It happily accesses a nonsensical index -1 of an array even though the array has only allowed indexes 0 to some value. May 27, 2022 at 5:16
  • The difference is not in how && works, but in how programming errors are treated. Java checks for invalid array accesses and raises an exception. C lets you stomp happily into invalid terrain and calls it "undefined behaviour", something the programmer has to avoid.
    – M Oehm
    May 27, 2022 at 5:17
  • @ThomasKläger But how does placing the same condition before or after another condition result in error. && operator should check both the conditions if the first one is true. May 27, 2022 at 5:24

1 Answer 1

4

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.