您的所有断言都通过了吗?
Do all of your assertions passed?
这是我在javascript中写二分查找代码时得到的语句。
我没有t know what
如果有人能解决这个错误。
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(素数, 73), 20); // 我在这一行出错,我不知道是怎么回事,因为索引 20 是 return 并且与 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中写二分查找代码时得到的语句。
我没有t know what
如果有人能解决这个错误。
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(素数, 73), 20); // 我在这一行出错,我不知道是怎么回事,因为索引 20 是 return 并且与 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));