0
Why is This Condition not working? Inserting Sort
Hey, I made an 'Insert-Sort' in Java and for some reason it works when the condition is in one position, and it doesnt work when i switch places between the expression before the '&&' and after. HOW? The Specific Sorting Function (code): static int[] insertSort(int[] arr){ for (int i = 1; i < arr.length; i++){ int current = arr[i]; int j = i - 1; while(j >= 0 && current < arr[j]){ arr[j + 1] = arr[j]; j--; } arr[j + 1] = current; } return arr; }
1 ответ
+ 1
&& operator always check first condition if it is false it doesn't check second one.
C1 && C2
if C1 is false C2 won't be checked.
for example when j<0 second part won't be checked so it won't cause index error in arr[j].
But when you flip them if j<0 arr[j] will cause index error