我需要找到素数索引,但我的 while 循环正在退出

I need to find the prime index but my while loop is exiting?

本文关键字:while 我的 循环 退出 索引      更新时间:2023-09-26

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);

  1. 您没有在min或移动max后更新猜测值。

  2. 循环返回第一次猜测,仅当猜测值等于搜索值时,才应执行此操作。