Created
April 19, 2010 20:02
-
-
Save anonymous/371519 to your computer and use it in GitHub Desktop.
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
static int binarySearch(int[] values, int val) throws Exception | |
{ | |
return binarySearchHelp(values, val, 0, values.length - 1); | |
} | |
static int binarySearchHelp(int[] values, int val, int start, int end) | |
throws Exception | |
{ | |
if (start > end) | |
throw new Exception("Somehow indexes have gotten reversed"); | |
if (start == end) | |
return values[start]==val ? start : -1; | |
int mid = (start + end) / 2; | |
if (values[mid] > val) | |
return binarySearchHelp(values, val, start, mid); | |
else if (values[mid] < val) | |
return binarySearchHelp(values, val, mid + 1, end); | |
else | |
return values[mid]==val ? mid : -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment