I was implementing recursive binary search and I ran into this problem that really confused me. Here is the code that I was initially running:
”’
int recursiveBinarySearch(int* arr, int start, int end, int key){
int middle = (start + end) / 2;
if (start >= end)return -1;
if (arr[middle] == key)return middle;
if (arr[middle] < key) {
recursiveBinarySearch(arr, middle+1, end, key);
}
if (arr[middle] > key) {
recursiveBinarySearch(arr, start, middle-1, key);
}
}
”’
Now, as far as I understand, as soon as a base case is reached, the only thing returned should be the value that is returned from the base-case because no other call is returning anything.
However, clearly I was wrong because this wasn’t giving correct answers and apparently I needed a return statement infront of each of the recursive call for this algo to work, as I found out later.
So my question is, why do we need to have the return statement? What exactly is the reason that my solution doesn’t work?
>Solution :
Let’s assume, X is the function we are calling from the main function. And there is a function Y which is being called from function X. Function Y does some computation and calculates the result for X. So you should just call function Y and return it’s result like below.
Y() {
// Some computation
return result;
}
X() {
return Y();
}
main() {
X();
}
Now think of it like this, each recursive call is a separate function that is doing some task. So your recursiveBinarySearch function should return the answer but it can’t compute that itself, so it is calling some other functions (which in this case the same function, thus call recursion) to get the result. So it will keep calling the function and break down the problems into smaller ones until it reaches the base case where it will get the answer and finally return it.