i am asking how this code is giving index 4 as first occurence of 5 but answer is 2.
Binary search doubt
share the link of complete code
Problem is in this function only, i am unable to find it else in the main function i have just passed first(arr,9(size of array),5(element i want to find)) but giving me 4 as output but the output is 2.
that i will check
if you share the link of code
to share the link of code
paste your code at https://ide.codingblocks.com/
to save the code press ctrl + s
and then share the link of code generated
#include
using namespace std;
int check1(int a[],int N,int x)
{
int low=0,ans=-1;
int high=N-1;
while(low<=high)
{
int mid=(low+high)/2;
if(a[mid]==x)
{
ans=mid;
high=mid-1;
}
if(a[mid]>x)
{
high=mid-1;
}
else
{
low=mid+1;
}
}
return ans;
}
int main()
{
int a[9]={1,2,5,5,5,5,7,23,25};
cout<<check1(a,9,5)<<" ";
return 0;
}
this is the code i am not getting desired output.
Kindly post new doubt now