I am trying to write a method where I can find the index of the desired number using binary search and recursion only. This is the method that I wrote:
public static int binSearch_r (int[] data, int value, int from, int to)
{
if (from <= to)
{
int middle = (from+to)/2;
if (data[middle] > value)
{
binSearch_r(data, value, from, middle - 1);
}
else if (data[middle] < value)
{
binSearch_r(data, value, middle+1, to);
}
else
{
return middle;
}
}
return -1;
}
data is the original array that is inputed, value is the number I am trying to find, from is the left most index of the array and to is the right most index of the array.
The array that I tested this method with is simply {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}. However, when I set value to 9, the initial "from" to 0 and the initial "to" to array.length-1, I receive -1 instead of the desired index. This happens for any number that I set for value. What am I doing wrong?
binSearch_rrecursive call. iereturn binSearch_r(data, value, from, middle - 1);