Created
May 17, 2019 17:51
-
-
Save Ikhan/1ce949cfc4539bdcfd45b9ca172b7b1c 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
function binarySearch(ar, elem) { | |
let start = 0; | |
let end = ar.length -1; | |
let mid = Math.floor((start + end) / 2); | |
while(ar[mid] !== elem && start < end ) { | |
if (elem < ar[mid]) end = mid - 1; | |
else start = mid + 1; | |
mid = Math.floor((start + end) / 2); | |
} | |
return ar[mid] === elem ? mid : -1; | |
} | |
binarySearch([1,2,5,6,7,9,10], 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment