Insertion Sort; Err: Outofbound

@nehauppal9,
Conditions are evaluated left to right.

Initially, for case j=-1 , your code wasn’t evaluating the second condition because the first one was throwing an ArrayIndexOutOfBoundsException exception.

			while (val > a[j] && j >= 0){

In the above condition, in case j=-1 , a[-1]>val will be evaluated first and that will give you an OutOfBoundsException run error.

However when you switched the conditions like this:

			while ( j >= 0 && val > a[j] ) {

then for the same case ( j=-1 ), since first condition becomes false , then regardless of the second value, the whole condition will always be false (because its AND operator); and so the second condition won’t be evaluated and hence no exception in this case.

1 Like