Skip to content

Instantly share code, notes, and snippets.

@lkptrzk
Created September 19, 2012 14:43
Show Gist options
  • Save lkptrzk/3750059 to your computer and use it in GitHub Desktop.
Save lkptrzk/3750059 to your computer and use it in GitHub Desktop.
javascript binary search
function binary_search(arr, search_term, min, max) {
if (max < min) return -1;
var i = Math.floor((min + max) / 2),
curr_term = arr[i];
if (curr_term === search_term) {
return i;
} else if (curr_term < search_term) {
return binary_search(arr, search_term, min, i - 1);
} else if (curr_term > search_term) {
return binary_search(arr, search_term, i + 1, max);
} else {
throw new Error("Problem comparing " + search_term + " to " + curr_term);
}
}​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment