0

我正在完成可汗学院二进制搜索算法挑战赛,我已经在这个网站上搜索了与该挑战赛相关的问题,但没有找到像我这样的问题。

我的问题是,为什么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);
4

1 回答 1

1

如果找到数字,while 循环内的 return 语句会将程序的控制权传递给调用函数。换句话说,它会从函数中出来。

如果 min > max,则意味着找不到给定的数字,它将退出 while 循环并返回 -1。

于 2015-09-05T17:21:11.900 回答