Skip to content

Instantly share code, notes, and snippets.

@Ikhan
Created May 17, 2019 17:51
Show Gist options
  • Save Ikhan/1ce949cfc4539bdcfd45b9ca172b7b1c to your computer and use it in GitHub Desktop.
Save Ikhan/1ce949cfc4539bdcfd45b9ca172b7b1c to your computer and use it in GitHub Desktop.
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