While learning recursion I tried to implement binary search.Both my functions provide the correct answer.Can someone explain why?
I feel that in the first function the recursive function return the values found to the previous functions but in the second function the recursive functions are just called and the call which hits the base case or which gets the answer returns directly to main().
Can someone please confirm if in the second case the function where the base case is reached or the element is found it's returned directly to main() and not to the previous recursive functions in the callstack, if there is one needed in the second case.
int bins1(int *arr,int l,int h,int el){
if(l>h){
return -1;
}
int mid = (l+h)/2;
if(arr[mid] == el){
return mid+1;
}
else if(arr[mid] > el){
return bins1(arr,mid+1,h,el);
}
else if(arr[mid] < el){
return bins1(arr,l,mid-1,el);
}
}
int bins2(int *arr,int l,int h,int el){
if(l>h){
return -1;
}
int mid = (l+h)/2;
if(arr[mid] == el){
return mid+1;
}
else if(arr[mid] > el){
bins2(arr,mid+1,h,el);
}
else if(arr[mid] < el){
bins2(arr,l,mid-1,el);
}
}