以下是用JS编写的简单二进制搜索代码。这段代码返回-1,而它应该返回20.在环顾四周之后我做了些事情:
将“while(min< max)”替换为“while(min< = max)”会在KhanAcademy上弹出错误。
我使用过Math.floor函数,由于某种原因会弹出错误“ env .Math.floor不是函数”,所以改为使用“Math.round”。
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while (min < max) {
guess = Math.round((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, 73);
console.log("Found prime at index " + result);
//print (primes[]);
//Program.assertEqual(doSearch(primes, 73), 20);
答案 0 :(得分:1)
我建议在分配新值时将min
rps max
值更改为guess
。
此外,我建议将Math.round
更改为Math.floor
。
(小提示:返回后,if
子句已结束,因此不需要else if
。)
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;
}
if (array[guess] < targetValue) {
min = guess;
} else {
max = 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],
result = doSearch(primes, 73);
console.log("Found prime at index " + result);
答案 1 :(得分:0)
这是最小和最大计算。 “+”和“ - ”信号相反。
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while (min < max) {
guess = Math.round((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, 73);
console.log("Found prime at index " + result);
//print (primes[]);
//Program.assertEqual(doSearch(primes, 73), 20);
答案 2 :(得分:0)
您的代码中只有一个小错误。您应该将min = guess + 1更改为min = guess - 1。
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while (min < max) {
guess = Math.round((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, 73);
console.log("Found prime at index " + result);
//print (primes[]);
//Program.assertEqual(doSearch(primes, 73), 20);