Skip to content

Instantly share code, notes, and snippets.

@erick2014
Created May 10, 2019 20:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erick2014/ebc866581cd6c5a14ef521751595baa1 to your computer and use it in GitHub Desktop.
Save erick2014/ebc866581cd6c5a14ef521751595baa1 to your computer and use it in GitHub Desktop.
/* Binary search algorithm implementation */
function binarySearch(items,valueToFind){
let start = 0
let stop = items.length-1
let middle = Math.floor( (start+stop) / 2 )
let itemFoundAtPos = -1
while( start < stop ){
let itemInMiddlePos = items[middle]
if(itemInMiddlePos === valueToFind){
itemFoundAtPos = middle;
break
}
if(valueToFind < itemInMiddlePos ){
stop = middle -1
}else{
start = middle +1
}
middle = Math.floor( (start+stop) / 2 )
}
if(items[middle] === valueToFind){
return middle
}
return itemFoundAtPos;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment