我需要找到素数索引,但我的 while 循环正在退出
I need to find the prime index but my while loop is exiting?
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess = Math.floor((min + max) / 2);
var values = array[guess];
while (min < max) {
if (values < targetValue) {
min = guess + 1;
} else if (values > targetValue) {
max = guess - 1;
}
return 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];
var result = doSearch(primes, 73);
alert("Found prime at index " + result);
现场演示
您需要在代码中修复多个问题,请查看我的评论:
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
var values;
while (min <= max) { // "less or equal" otherwise some case won't work
guess = Math.floor((min + max) / 2); // guess needs to be assigned every loop
values = array[guess]; // values need to be updated in every loop
if (values < targetValue) {
min = guess + 1;
} else if (values > targetValue) {
max = guess - 1;
} else{
return guess // This is only when values == targetValue, if no else was used, it will return from the first loop
}
}
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);
alert("Found prime at index " + result);
-
您没有在
min
或移动max
后更新猜测值。 -
循环返回第一次猜测,仅当猜测值等于搜索值时,才应执行此操作。
相关文章:
- 为什么不't Javascript对我的输入值进行了一些重新检查
- 可以't让我的if语句处理js中的html表单输入
- 我的单元测试选项是什么
- 将输入字段中的文本提交到我的数据库,同时将其添加到我的列表中
- 我的职位回报太快了,如何做出承诺
- 为什么我的While循环不起作用
- 有人可以向我解释javascript getCookie()中while循环的功能吗?
- 为什么我的 while 循环没有完全迭代
- 我需要找到素数索引,但我的 while 循环正在退出
- 为什么我的while循环是无限的?每次都更改变量,但条件仍然始终为真
- 为什么获胜'我的While Loop工作
- 我的do while循环陷入了无限循环
- 试着写一个do-while循环语句来打印我的语句,但是它目前没有打印它
- 为什么我的javascript不在这个while循环中改变bg的颜色?
- 初学者:试图用do while循环来实现我的想法,把我的头弄破了
- 我的while循环是'不工作
- l'我被javascript while语句的使用弄糊涂了
- Javascript-我的setTimeOut在while循环中没有'不起作用
- 用确认框停止我的 while 循环
- (JS)为什么我的While循环不工作!也许我不理解这个基本概念