Created
July 7, 2016 22:13
-
-
Save tkreis/252c36b231a356553ed568f9a9937189 to your computer and use it in GitHub Desktop.
Simple Binary Search
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() { | |
this.search = function (needle, haystack) { | |
var middle = parseInt(haystack.length/2), | |
compareAgainst = haystack[middle]; | |
if(needle == compareAgainst) { return needle; } | |
if(needle < compareAgainst) { return this.search(needle, haystack.slice(0, middle))} | |
if(needle >= compareAgainst) { return this.search(needle, haystack.slice(middle))} | |
return false; | |
} | |
} | |
b = new BinarySearch(); | |
x = [1,2,3,4,5,6,7,8,9,10,11,12]; | |
console.log(b.search(10, x)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment