如何在JavaScript中实现二分查找

4

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

while 循环中,检查 array[min]==targetarray[max]=target - Junle Li
´println()´在Javascript中不是一个函数。我认为你想用´console.log()´代替它:https://developer.mozilla.org/en-US/docs/Web/API/Console/log - Jacob Lauritzen
4个回答

13

要从数组中获取一个值,你需要指定一个整数,比如array[1]。在这种情况下,array[1.25]将返回undefined

为了使其工作,我只需在你的循环内添加Math.floor,以确保我们获得一个整数。

编辑:正如@KarelG指出的那样,你还需要在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;
}

你可以使用Math.floorMath.ceilMath.round中的任何一个。

希望这有所帮助,我不太擅长解释,但我会尽力阐述。


在 while 循环中需要使用 <=。尝试通过搜索 11 来运行您的代码。 - KarelG
为什么不用 Math.round?请解释一下。 - Begginer
@初学者非常抱歉,我的错。Math.round同样很好!已编辑答案。 - Jacob Lauritzen

2

在您的代码中,当min等于max时,循环将结束。但在这种情况下,您没有检查array [min] == targetValue

因此,将代码更改为以下内容可能会解决您的问题

/* 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 = 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;
};

JSFiddle链接: http://jsfiddle.net/7zfph6ks/

希望能对您有所帮助。

附注: 代码中唯一的更改是这一行:while (min <= max)


有人可以解释一下为什么要点踩并且为什么这条评论应该被删除吗? - Diptendu
我没有给你点赞,但是请自行尝试代码。我怀疑它不会有效。 - KarelG

1

您只需要取消注释Program.assertEqual,像这样:

Program.assertEqual(doSearch(primes, 73), 20);

不要像这样:

//Program.assertEqual(doSearch(primes, 73), 20);

0

如果还有人在寻找答案,你需要使其 (max >= min)

while (max >= min) {
 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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接