Skip to content

Instantly share code, notes, and snippets.

@jeffscottward
Created August 5, 2019 16:02
Show Gist options
  • Save jeffscottward/b6358da0ac1354d5d58aad58df229ba3 to your computer and use it in GitHub Desktop.
Save jeffscottward/b6358da0ac1354d5d58aad58df229ba3 to your computer and use it in GitHub Desktop.
Binary Search Example
const doSearch = function (array, targetValue) {
let minIndex = 0;
let maxIndex = array.length - 1;
let guessIndex;
console.log(minIndex,maxIndex,guessIndex)
while(maxIndex >= minIndex){
guessIndex = Math.floor((maxIndex+minIndex)/2)
console.log({minIndex, max, guessIndex});
console.log('==========');
console.log(array[guessIndex], targetValue);
console.log("==========");
if(array[guessIndex] === targetValue) {
return guessIndex
} else if ( array[guessIndex] < targetValue ) {
minIndex = guessIndex + 1;
} else {
max = guessIndex -1
}
}
return -1 // value not present
}
const array = [ 0, 8, 16, 20, 45, 65, 89, 100]
console.log(doSearch(array, 89))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment