Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Binary search algorithm in javascript
var binarySearch = function(array, value) {
var guess,
min = 0,
max = array.length - 1;
while(min <= max){
guess = Math.floor((min + max) /2);
if(array[guess] === value)
return guess;
else if(array[guess] < value)
min = guess + 1;
else
max = guess - 1;
}
return -1;
}
@pichayean
Copy link

`//Copyright 2009 Nicholas C. Zakas. All rights reserved.
//MIT-Licensed, see source file
function binarySearch(items, value){

var startIndex  = 0,
    stopIndex   = items.length - 1,
    middle      = Math.floor((stopIndex + startIndex)/2);

while(items[middle] != value && startIndex < stopIndex){

    //adjust search area
    if (value < items[middle]){
        stopIndex = middle - 1;
    } else if (value > items[middle]){
        startIndex = middle + 1;
    }

    //recalculate middle
    middle = Math.floor((stopIndex + startIndex)/2);
}

//make sure it's the right value
return (items[middle] != value) ? -1 : middle;

}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment