As shown below is the basic insertion sort algorithm taught at school. if you change the order of while loop parameters, it doesn't work.
public static int[] insertionSort(int[] A){
for(int i =1; i<A.length;i++){
int key = A[i];
int j = i;
while(j>0&&A[j-1]>key){
A[j]=A[j-1];
j--;
}
A[j]=key;
}
return A;
}
After the change (Now the code wont work and it will give java.lang.ArrayIndexOutOfBoundsException: -1 expection):
public static int[] insertionSort(int[] A){
for(int i =1; i<A.length;i++){
int key = A[i];
int j = i;
while(A[j-1]>key&&j>0){
A[j]=A[j-1];
j--;
}
A[j]=key;
}
return A;
}
If there any other way to implement the same algorithm so that the order of the conditional loop statements doesn't matter?
Because of short-circuit evaluation.
If the first half of an &&
is false, the second half will not be evaluated at all (since the result cannot possibly be true).
Therefore, you can write j > 0 && A[j - 1]...
, and A[j - 1]
will only be evaluated if j > 0
.