Skip to content

Instantly share code, notes, and snippets.

@C-Rodg
Created November 4, 2016 01:42
Show Gist options
  • Save C-Rodg/8d1bbda658541a3597531967d4769868 to your computer and use it in GitHub Desktop.
Save C-Rodg/8d1bbda658541a3597531967d4769868 to your computer and use it in GitHub Desktop.
A binary search algorithm for sorted arrays. More efficient than the Array's 'indexOf' method
function binarySearch(items, value) {
let startIndex = 0,
stopIndex = items.length - 1,
middle = Math.floor((startIndex + stopIndex) / 2);
while(value !== items[middle] && startIndex < stopIndex) {
if(value < items[middle]) {
stopIndex = middle - 1;
} else if (value > items[middle]) {
startIndex = middle + 1;
}
middle = Math.floor((stopIndex + startIndex) / 2);
}
return (value === items[middle]) ? middle : -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment