0
Can somebody tell me why in the code
while (currentRight < array.length - 1)... Why is it currentRight less than array.length -1. When the element we are searching for can be present in the index .. array.length-1. https://code.sololearn.com/cpkgTT33biXc/?ref=app
1 Odpowiedź
+ 1
I think it has to do with the calculation of currentRight:
currentRight = Math.min(array.length - 1, currentRight + jumpLength);
jumpLength is 3.
currentRight is 0.
inside while loop:
Min (8, 0 + 3) = 3
Min (8, 3 + 3) = 6
Min (8, 6 + 3) = 8
8 == array.length - 1 -> the while condition gets false -> break the loop
now you can jump into the linear search and get 35 as output.
while (currentRight < array.length) would return true because 8 < 9 is true. You would do the loop again.
currentRight = Min (8, 8 + 3) = 8
if (array[currentRight] >= target) {
break;
}
array [8] >= 35 returns true.
the loop would break here.
So while (currentRight < array.length - 1) prevents an unnecessary execution of the loop.
I hope it helps :)