如何在JavaScript中实现二进制搜索
问题内容:
https://www.khanacademy.org/computing/computer-science/algorithms/binary-
search/p/challenge-binary-
search
我遵循伪代码在链接上实现算法,但不知道我的代码出了什么问题。
这是我的代码:
/* 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 = (max + min) / 2;
if (array[guess] === targetValue) {
return guess;
}
else if (array[guess] < targetValue) {
min = guess + 1;
}
else {
max = guess - 1;
}
}
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, 2);
println("Found prime at index " + result);
//Program.assertEqual(doSearch(primes, 73), 20);
问题答案:
要从数组中获取值,您需要指定一个整数,例如array[1]
。array[1.25]
将返回undefined
您的情况。
为了使它正常工作,我只是Math.floor
在循环内添加了一个以确保我们得到一个整数。
编辑:作为@KarelG指出,您还需要<=
在while循环中添加。这适用于min
和max
变得相同的情况,在这种情况下guess === max === min
。如果没有<=
循环,则在这些情况下将无法运行,函数将返回-1
。
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;
}
}
return -1;
}
你可以使用任何一种Math.floor
,Math.ceil
和Math.round
。
我希望这是一个小帮助,我不太会解释,但我会尽力而为。