Javascript Khan academy算法:二进制搜索解决方案
我在汗学院学习算法: 下面大部分代码的结果是-1?为什么呢? 所以二进制搜索不会有效地工作Javascript Khan academy算法:二进制搜索解决方案,javascript,khan-academy,Javascript,Khan Academy,我在汗学院学习算法: 下面大部分代码的结果是-1?为什么呢? 所以二进制搜索不会有效地工作 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
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;
}
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];
for(var i=0;i<primes.length;i++){
var result = doSearch(primes,primes[i]);
console.log("Found prime at index of " + primes[i] +" @ " + result);
}
我遗漏了什么?您过早终止循环-
min==max
是一个有效条件
将循环更改为
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;
}
}
假设您的列表只有2个素数,您搜索较大的素数。您的循环将针对较小的失败进行测试,并将
min
设置为与max
相同,因此循环将在检查该值之前终止
你的循环保护应该是
min@JoachimPileborg你确定这是什么意思?为什么我被否决了?我一直在关注这个小提琴@JoachimPileborg,不是吗?好像是的。@JoachimPileborg是这样吗?你能给我指出一个正确的平均值表达式吗?我显然还没醒。很抱歉造成混淆。这里的问题不是效率,而是正确性。
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;
}
}
VM153:30 Found prime at index of 2 @ 0
VM153:30 Found prime at index of 3 @ 1
VM153:30 Found prime at index of 5 @ 2
VM153:30 Found prime at index of 7 @ 3
VM153:30 Found prime at index of 11 @ 4
VM153:30 Found prime at index of 13 @ 5
VM153:30 Found prime at index of 17 @ 6
VM153:30 Found prime at index of 19 @ 7
VM153:30 Found prime at index of 23 @ 8
VM153:30 Found prime at index of 29 @ 9
VM153:30 Found prime at index of 31 @ 10
VM153:30 Found prime at index of 37 @ 11
VM153:30 Found prime at index of 41 @ 12
VM153:30 Found prime at index of 43 @ 13
VM153:30 Found prime at index of 47 @ 14
VM153:30 Found prime at index of 53 @ 15
VM153:30 Found prime at index of 59 @ 16
VM153:30 Found prime at index of 61 @ 17
VM153:30 Found prime at index of 67 @ 18
VM153:30 Found prime at index of 71 @ 19
VM153:30 Found prime at index of 73 @ 20
VM153:30 Found prime at index of 79 @ 21
VM153:30 Found prime at index of 83 @ 22
VM153:30 Found prime at index of 89 @ 23
VM153:30 Found prime at index of 97 @ 24