Skip to content

Instantly share code, notes, and snippets.

@alexander-williamson
Created August 27, 2019 14:50
Show Gist options
  • Save alexander-williamson/07f3a2c9cd9a2f0267b5e6f19f09089d to your computer and use it in GitHub Desktop.
Save alexander-williamson/07f3a2c9cd9a2f0267b5e6f19f09089d to your computer and use it in GitHub Desktop.
Binary Search Kata in Javascript
function binSearch(arr, toSearch) {
var lowerBound = 0, upperBound = arr.length -1;
while(true) {
var index = Math.floor((upperBound - lowerBound) / 2 + lowerBound);
var current = arr[index];
if(current === toSearch) return index;
if(current > toSearch) {
upperBound = upperBound - Math.floor((upperBound - lowerBound) / 2)
}
if(current < toSearch) {
lowerBound = lowerBound + Math.ceil((upperBound - lowerBound) / 2);
}
if (upperBound === lowerBound) return -1;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment