Java recursive binary search throwing out of bounds exception?
Hey, I have been asked to write a recursive binary search for my data structure class in university, but i'm having a slight problem. When i search for a number that is out of bounds (over 10 in this case) it throws an out of bounds exception. I understand why it's doing it, due to the array not having >10 spaces, but i don't know how to work around it. Any ideas?
The array that im searching is an ordered array 1开发者_如何学Go - 10 (index 0 - 9).
public int recursiveBinarySearch(int[] anArray, int searchedNumber, int min, int max) {
if (min > max)
{
System.out.println(searchedNumber + " is not present in tha array.");
//return -1 to show that the value has not been found
return -1;
}
// find the centre of the array
int centre = (min + max) / 2;
if (anArray[centre] == searchedNumber)
{
System.out.println(searchedNumber + " was found at index " + centre);
return centre;
}
if (anArray[centre] < searchedNumber)
{
return recursiveBinarySearch(anArray, searchedNumber, centre+1, max);
}
return recursiveBinarySearch(anArray, searchedNumber, min, centre-1);
}
public int recursiveBinarySearch(...) {
if (max >= array.length) {
max = array.length - 1;
}
if (min < 0) {
min = 0;
}
... rest of the code
}
PS Not to be a nagger, but I would also recommend using consistent indentation. Believe me, it helps greatly in writing bug-free programs.
I suppose it starts with min = 0
and max = 9
, then it goes
min = 0, max = 9, c = (0+9 / 2) = 4
min = 5, max = 9, c = (6+9 / 2) = 7
min = 8, max = 9, c = (8+9 / 2) = 8
min = 9, max = 9, c = (9+9 / 2) = 9
min = 10, max = 9, ...
As you can see it gets over the bound, min = 10
will of course cause problems. To avoid that just widen the initial condition:
if (min > max || min > Array.length -1 || max < 0)
// not found!
so that if your going over the array in any of two directions then the requested element won't be found.
精彩评论