【发布时间】:2018-06-15 00:27:45
【问题描述】:
为什么我的算法返回“-1”意味着目标值 73 不在数组中? (当明显 73 在数组中时)。 [这是来自可汗学院,但没有帮助]
它应该返回数组中位置的索引, 如果数组不包含目标值,则为“-1”
Var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
while(max >= min) {
guess = floor((max*1 + min*1) / 2);
if (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);
【问题讨论】:
-
guess = floor你能发布你的floor函数吗? (假设它不同于Math.floor) -
写
max*1和min*1有什么意义。乘以 1 不会改变数字。 -
你已经在你的代码中指定了“return -1”
-
你甚至没有遍历数组。您的函数将始终返回 -1。
-
@HoCo_ 你可能错过了另一个
return声明。我已经对问题进行了格式化以使其更清晰
标签: javascript binary-search khan-academy