我正在完成可汗学院二进制搜索算法挑战赛,我已经在这个网站上搜索了与该挑战赛相关的问题,但没有找到像我这样的问题。
我的问题是,为什么return -1;
表达式不是条件语句的一部分,-1
只有在搜索的素数不在数组中的情况下才返回结果?
我已经设法自己解决了挑战,但那是因为这部分功能已经由挑战赋予。所以我不明白为什么在下面的函数中,return -1;
在while
循环之后出现,并且似乎适用于任何条件。在我看来,这似乎会产生数组中-1
是否存在的结果targetValue
(即使事实并非如此,并且该函数按应有的方式工作)。
/* 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);