I am doing some exercises so that I can get through recursive stuff. One of these is I’m trying to re-write the linear search with recursion. Here it is:
int linearSearch(int a[], int n, int key)
{
if (n < 0 )
{
return -1;
}
if(key == a[n-1])
{
return n - 1;
}
linearSearch(a, n-1, key); // Line 1
}
The code did not execute correctly if it does not have return statement. I dont understand why we need to put the return statement at line 1? Is all we need to call recursively in this case just to decrease n by 1?
You should
returnthe value from the recursive invokation:Otherwise, the answer is not bubbling its way up to the first invokation of the function, and will not be returned as an “answer” to the original caller.
The base clauses that return
n-1or-1– are just returning it to their caller, which is the same function! but without returning it from there, it will never reach the original caller.