这是我在 javascript 中编写二进制搜索代码时得到的语句。
我不知道错误是什么
如果有人能解决这个问题。
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while(min <= max)
{
guess = Math.floor((min+max)/2);
if(array[guess] === targetValue)
{
return guess;
}
else if(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, 73);
println("Found prime at index " + result);
Program.assertEqual(doSearch(primes, 73), 20);//我在这一行出错,我不知道是怎么回事,因为返回索引 20 并与 20 进行比较,但它仍然很糟糕!!!
最佳答案
您需要检查值,而不是针对 targetValue
的索引
} else if (array[guess] < targetValue) {
// ^^^^^^^^^^^^
var doSearch = function(array, targetValue) {
var min = 0,
max = array.length - 1,
guess;
while (min <= max) {
guess = Math.floor((min + max) / 2);
if (array[guess] === targetValue) {
return guess;
}
// no need for else, because return terminates the function
if (array[guess] < targetValue) { // use the item, not the index
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
];
console.log(doSearch(primes, 73));
关于javascript - 您的所有断言都通过了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45631931/