Binary search in recursion

the code below is my code for binary search using recursion after I wrote it and just googled the code if I had written correctly or not but I found on websites a different code using mid value passing first and last value of array in binary search function so is my code any wrong or the website are making things complicated ?

#include <bits/stdc++.h>
using namespace std;

int binarysearch(int a[],int n,int no)
{
if (n>=1)
{
if(a[n/2]==no)
{
return (n/2);
}
else if (a[n/2]>no)
{
return binarysearch(a,n/2,no);
}
else if (a[n/2]<no)
{
return binarysearch(&a[n/2]+1,n/2-1,no);
}
}
else
return -1;

}

int main(){

int a[]={10,12,19,22,25};
int n = sizeof(a)/sizeof(int);
int f;
cin>>f;
cout<<(binarysearch(a,n,f));

}

Actually your code is wrong. It might not work in some cases. In recursive function of binary search, we always pass start and end index of the array so that mid value can be calculated within the function by (start+end)/2. And then accordingly we move to the left or right parts.

1 Like

can you please guide me for which cases this code might not work :thinking:

Try taking arrays of even and odd lengths. And dry run on them. If this code is getting all test cases right on submission, then its fine.

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.