I have a little confusion in the following two statements.
The below program is finds the index of an element out of a sorted array[no duplicates] using binary search.
int bin(int *arr,int l,int h,int k)
{
int mid;
if(l>h)
return -1;
if(l==h)
{
return arr[l]==k?l:-1;
}
else
{
mid=(l+h)>>1;
if(arr[mid]==k)
return mid;
else if(k>arr[mid])
bin(arr,mid+1,h,k);
else
bin(arr,l,mid-1,k);
}
}
I do not have any problem in the program[working perfectly]:
I have confusion in following two statements:
bin(arr,l,mid-1,k); http://ideone.com/p1o5U
return bin(arr,l,mid-1,k); http://ideone.com/lMhgB
Using any of the above statement gives correct result.
Which statement is more efficient in terms of time?
How the program is working fine even without return statement?
In this case I’d say there is no difference in practice, as the recursion ends to a return statement irrelevant of which parameters you give to it (yes, even though you don’t specify it in the last two calls). This is however a compiler-specific detail that you should not rely on!
You might consider the ones with the return statement a bit more efficient as in that case it doesn’t need to read up on the “else” check, however, the difference is very small.
Do note however that without return statements it is considered “incorrect”, even though it “works”, and -Wall should give you warnings about it.
See this similar question also. Copied from that answer:
Edit: changed the wording as to not imply the behaviour as a deliberate optimization. Don’t know if it is or not. It is anyway something that some compilers do and some don’t.