Search code examples
javascriptarraysassert

Do all of your assertions passed?


This is a statement I get when I write a code of binary search in javascript. I dont know whats the error If someone could sort this.

        var doSearch = function(array, targetValue) {
        var min = 0;
    var max = array.length - 1;
    var guess;
    while(min <= max)
    {
        guess = Math.floor((min+max)/2);
        if(array[guess] === targetValue)
        {
        return guess;
        }
        else if(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, 73);
println("Found prime at index " + result);

Program.assertEqual(doSearch(primes, 73), 20); // I get error on this line, I don`t know what is the matter , because the index 20 is return and compares to 20 but it stills sucks !!!


Solution

  • You need to check the value, not the index against the targetValue

    } else if (array[guess] < targetValue) {
    //         ^^^^^^^^^^^^
    

    var doSearch = function(array, targetValue) {
        var min = 0,
            max = array.length - 1,
            guess;
    
        while (min <= max) {
            guess = Math.floor((min + max) / 2);
            if (array[guess] === targetValue) {
                return guess;
            }
            // no need for else, because return terminates the function
            if (array[guess] < targetValue) { // use the item, not the index
                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
    ];
    
    console.log(doSearch(primes, 73));