Very easy to undersand cpp sol


#1

int bsd(vector A,int l,int h,int b)//binary search for descending array
{
int m;
while(l<=h)
{
m=(l+h)/2;
if(A[m]==b)
return m;
if(A[m]<b)
h=m-1;
else
l=m+1;
}
return -1;
}
int bs(vector A,int l,int h,int b)//binary search for ascending array
{
int m;
while(l<=h)
{
m = (l+h)/2;
if(A[m]==b)
return m;
if(A[m]<b)
l=m+1;
else
h=m-1;
}
return -1;

}
int bpt(vector A,int l,int h)//finding the bitonic pt.(bpt)
{
int m=(l+h)/2;
while(!(A[m]>A[m+1] && A[m]>A[m-1]))
{
if(A[m]<A[m+1] && A[m-1]<A[m])
l=m+1;
else
h=m-1;
m=(l+h)/2;
}
return m;
}
int Solution::solve(vector &A, int B) {
int b=bpt(A,0,A.size()-1);
int ans;
if(A[b]==B)//if bitonic pt. is the answer
return b;
else
{
//if else condition to check whether to go to left or right of bpt.
if(A[b-1]>=B)
ans=bs(A,0,b-1,B);
else
ans=bsd(A,b+1,A.size()-1,B);
}
return ans;
//Both bsd and bs can be combined by passing an extra parameter as a bool to just check
//whether array is ascending or descending
}