Skip to content

Instantly share code, notes, and snippets.

@cbdavide
Last active April 30, 2022 02:18
Show Gist options
  • Save cbdavide/97100ac68e1f3699274b38a3d6bde7ba to your computer and use it in GitHub Desktop.
Save cbdavide/97100ac68e1f3699274b38a3d6bde7ba to your computer and use it in GitHub Desktop.
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