Skip to content

Instantly share code, notes, and snippets.

@tkreis
Created July 7, 2016 22:13
Show Gist options
  • Save tkreis/252c36b231a356553ed568f9a9937189 to your computer and use it in GitHub Desktop.
Save tkreis/252c36b231a356553ed568f9a9937189 to your computer and use it in GitHub Desktop.
Simple Binary Search
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