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 - 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);
}