Skip to content

Instantly share code, notes, and snippets.

@methodin
Created December 28, 2011 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save methodin/1525937 to your computer and use it in GitHub Desktop.
Save methodin/1525937 to your computer and use it in GitHub Desktop.
Binary Search in JS
function binarySearch(searchFor, arr, index1, index2) {
if(index1 === undefined) index1 = 0;
if(index2 === undefined) index2 = arr.length-1;
var search = index1+Math.floor((index2-index1)/2);
if(arr[search] == searchFor) return true;
else if(index2-index1 <= 1) return false;
else return binarySearch(searchFor, arr, arr[search] > searchFor ? index1 : search, arr[search] > searchFor ? search : index2);
}
var found = binarySearch(4, [1,3,6,9,12,17,25,44]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment