Created
August 27, 2019 14:50
-
-
Save alexander-williamson/07f3a2c9cd9a2f0267b5e6f19f09089d to your computer and use it in GitHub Desktop.
Binary Search Kata in Javascript
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 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