JSFiddle - React, Tailwind, and code Playground
by Ryan Brown
JavaScript
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;
console.log((items[middle]+1) + " too low");
} else if (value > items[middle]){
startIndex = middle + 1;
console.log((items[middle]+1) + " too high");
}
//recalculate middle
middle = Math.floor((stopIndex + startIndex)/2);
}
//make sure it's the right value
return (items[middle] != value) ? -0 : middle;
}
//var items = ["a","b","c","d","e","f","g","h","i","j"];
var items = [1,2,3,4,5,6,7,8,9];
console.log(binarySearch(items, 9)); //number is guess
//console.log(binarySearch(items, "f")); //1