Here is the code:- https://ide.codingblocks.com/s/426372, please tell the error, it is giving element is found whether or not the element is present.
Binary Search using Recursion
Check now ->
The code is for linear search for binary search you have to calculate mid too and pass it as an argument.
i+1 & n-1 doesn’t not work for binary search.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
Yes, I got it that I was actually applying linear search, but not getting how passing of i is making a difference in it, like in binary search we used to have mid=(s+e)/2, so here i is 0 initially and then it would increment by one in every call.
Exactly …
make i=0, then every recursive call will increment value of i every time. Until i is less then n or arr[i] != key
Hey, I am not getting it how is it making a binary search, coz if suppose element is present at n-1 position, so till then n-2 calls would have been made, so how does it making a binary search, either it should be like we are making calls at half size and using the part in which answer could be find and discarding other part, something like this. Please explain this part, am not getting how is this binary search and was the difference in mine approach then.
Till now i was talking about linear search, but if you want to ask for binary search
Then look at this approach
We calculate mid after every recursive call by updating our start and end point.
I am not getting why we are returning -1 at the end of all if else conditions, like when will the call would reach to the end. The base case is returning -1 if s<e and also then atleast any one of the conditions will hold and value will also get returned from there directly, so how is that we need to return -1 there? Please explain.
Since the function is of int data type, so we have to return any integer value. Although this condition is used just to be safe that if we left any condition that is to be considered , we return -1 . Also this doubt has been closed, post a new thread if you have any other doubts left regarding this.