Skip to content

Instantly share code, notes, and snippets.

Created April 19, 2010 20:02
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 anonymous/371519 to your computer and use it in GitHub Desktop.
Save anonymous/371519 to your computer and use it in GitHub Desktop.
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