如何在JavaScript中实现二进制搜索

Beg*_*ner 2 javascript algorithm binary-search bisection

https://www.khanacademy.org/computing/computer-science/algorithms/binary-search/p/challenge-binary-search

我正在遵循伪代码在链接上实现算法,但不知道我的代码有什么问题.

这是我的代码:

/* Returns either the index of the location in the array,
  or -1 if the array did not contain the targetValue */

    var doSearch = function(array, targetValue) {
    var min = 0;
    var max = array.length - 1;
    var guess;

    while(min < max) {
        guess = (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, 2);
println("Found prime at index " + result);

//Program.assertEqual(doSearch(primes, 73), 20);
Run Code Online (Sandbox Code Playgroud)

Jac*_*zen 11

要从数组中获取值,您需要指定一个整数array[1].array[1.25]undefined在你的情况下返回.

为了让它工作,我只需Math.floor在你内部添加循环,以确保我们得到一个整数.

编辑:作为@KarelG pointet你也需要添加<=你的while循环.这对于情况minmax已经成为一样的,在这种情况下guess === max === min.没有<=循环不会在这些情况下运行,函数将返回-1.

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;
}
Run Code Online (Sandbox Code Playgroud)

你可以使用任何一种Math.floor,Math.ceilMath.round.

我希望这是一个很小的帮助,我不是很擅长解释,但我会做的就是详细说明.