Created
September 19, 2012 14:43
-
-
Save lkptrzk/3750059 to your computer and use it in GitHub Desktop.
javascript 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 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