I'm working through the Khan Academy Binary Search Algorithm Challenge and I've searched through the questions related to that challenge on this site, but haven't found a question like mine related to it.
My question is why the return -1;
expression isn't part of a conditional statement such that the result -1
is returned only in case the prime number being searched for isn't in the array?
I've managed to solve the challenge on my own but that's because this part of the function is already given by the challenge. So I don't understand why in the function below, return -1;
comes at the end after the while
loop and seems to apply in any condition. This would seem to me to yield a result of -1
whether or not the targetValue
is in the array (even though that's not in fact the case and the function works as it should).
/* Returns either the index of the location in the array,
or -1 if the array did not contain the targetValue */
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while(min <= max) {
guess = Math.floor((max + min)/2);
if(array[guess]===targetValue) {
return guess;
}
else if(array[guess] < targetValue) {
min = guess + 1;
}
else {
max = guess - 1;
}
println(guess);
}
return -1;
};
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
var result = doSearch(primes, 73);
println("Found prime at index " + result);
If the number is found, the return statement inside the while loop will pass the control of the program to the calling function. In other words, it will come out of the function.
If min > max, it implies that the given number couldn't be found and it will come out of the while loop and return -1.