Created
August 5, 2019 16:02
-
-
Save jeffscottward/b6358da0ac1354d5d58aad58df229ba3 to your computer and use it in GitHub Desktop.
Binary Search Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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