JSFiddle - React, Tailwind, and code Playground
by Diya_Khan
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;
} 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;
}
var items = ["a","b","c","d","e","f","g","h","i","j"];
document.write(binarySearch(items, "i") + '<br/>'); //8
document.write(binarySearch(items, "b") + '<br/>'); //1
function binarySearchEventsFromStartTime(items, value){
var startIndex = 0,
stopIndex = items.length - 1,
middle = Math.floor((stopIndex + startIndex)/2);
while(value >= items[middle].eventStartTime() && startIndex < stopIndex){
//adjust search area
if (value < items[middle].eventStartTime()){
stopIndex = middle - 1;
} else if (value > items[middle].eventStartTime()){
startIndex = middle + 1;
}
//recalculate middle
middle = Math.floor((stopIndex + startIndex)/2);
}
//make sure it's the right value
return (items[middle] != value) ? -1 : middle;
}