Skip to content

Instantly share code, notes, and snippets.

@motiooon
Created January 14, 2014 17:09
Show Gist options
  • Save motiooon/8421888 to your computer and use it in GitHub Desktop.
Save motiooon/8421888 to your computer and use it in GitHub Desktop.
Binary Search
function bSearch(items, value){
var startIndex = 0;
var stopIndex = items.length-1;
var middle = Math.floor((startIndex + stopIndex)/2);
while(value !== items[middle] && startIndex < stopIndex){
if(value > items[middle]){
startIndex = middle + 1;
}else if(value < items[middle]){
stopIndex=middle-1;
}
middle = Math.floor(( startIndex + stopIndex ) / 2);
}
return (items[middle] === value) ? middle : -1;
};
var items = [1, 3, 7, 9, 23, 34, 45, 52, 65, 67, 76, 82, 84, 86, 92, 100, 104, 121];
console.log("34 is at index: ", bSearch(items, 34));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment