I've been tasked with creating a binary search in Java using recursion. However, even though I specify return values, it is still telling me I must return an int result. Here are relevant parts of my code:
I've tried adding a return outside of the if-else statements, only to receive a StackOverflowError.
result = binarySearch(numbers, 0, numbers.length-1, search);
if(result==-1)
System.out.println("Value not found.");
else
System.out.println(search + " was found at index " + result);
}
public static int binarySearch(int n[], int f, int l, int val) {
if(f>l)
return -1;
else {
int mid = (f+l)/2;
if(val == mid)
return n[mid];
else {
if(val < mid)
binarySearch(n, f, mid-1, val);
if(val > mid)
binarySearch(n, f, mid+1, val);
}
}
}
I expected as follows: a value search is collected from the user and passed into the binarySearch method. The binarySearch method should then search my int array numbers from a starting value of 0 to the final value to find this value. In the binarySearch method, I believe that my logic is correct. When the initial low value is greater than the initial high value, that means that the search has completed and no result was found, so return -1. Otherwise, the item is in the array, so create a value mid to set the middle for the search. If the value being searched for is equal to middle, return the index that it was found at. If the value is less than the middle, then reduce the high value and run the search again, as the number must be to the left of the middle. If the value is greater than the middle, increase it and rerun as it must be to the right. Am I correct with my understanding of this? Why is it not recognizing the return inside the if-else statements?
Any help would be appreciated. Thanks.
The logic is correct, you will just need to return after the recursion is complete along with replacing the two of comparing val
and mid
by if/else. The modified recursive function would be like this:
public static int binarySearch(int n[], int f, int l, int val) {
if(f>l){
return -1;
} else {
int mid = (f+l)/2;
if(val == mid) {
return n[mid];
} else {
if(val < mid) {
return binarySearch(n, f, mid-1, val);
} else {
return binarySearch(n, mid+1, l, val);
}
}
}
}