2

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

4 に答える 4

2

あなたのコードでは、最小値が最大値と等しい場合、ループが終了します。しかし、このシナリオでは、チェックしていないかどうか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/

それが役に立てば幸い。

PS: コードの変更は次の行のみです。while (min <= max)

于 2015-04-06T08:56:00.203 に答える
1

次のように Program.assertEqual のコメントを外すだけです。

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

このようではありません:

//Program.assertEqual(doSearch(primes, 73), 20);
于 2015-08-27T13:57:46.340 に答える