Created
May 10, 2019 20:32
-
-
Save erick2014/ebc866581cd6c5a14ef521751595baa1 to your computer and use it in GitHub Desktop.
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
/* 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