Using binary search in C++


#1

int Solution::findCount(const vector &A, int B) {
int n=A.size();
int start=0,end=n-1,mid,count=0;
while(start<=end)
{
mid=(start+end)/2;
if(A[mid]==B)
{
count++;
int i=1;
while(mid-i>=start&&A[mid-i]==B)
{
count++;
i++;
}
i=1;
while(mid+i<=end&& A[mid+i]==B)
{
count++;
i++;
}
return count;
}
if(A[mid]<B)
{
start=mid+1;
}
else
{
end=mid-1;
}
}
return count;
}