转自https://blog.csdn.net/weixin_42165981/article/details/87277006?tdsourcetag=s_pctim_aiomsg
查找最后一个等于x的元素:
int search(const int *a,int n,int key)
{
int l=0,r=n-1,mid=0,ans=0;
while(l<=r)
{
mid=(l+r)/2;
if(a[mid]<=key) l=mid+1,ans=mid;
else r=mid-1;
}
return a[ans]==key?ans:-1;
}
查找第一个等于x的元素:
int search(const int *a,int n,int key)
{
int l=0,r=n-1,mid=0,ans=0;
while(l<=r)
{
mid=(l+r)/2;
if(a[mid]<key) l=mid+1;
else r=mid-1,ans=mid;
}
return a[ans]==key?ans:-1;
}
实数域上的二分:(注意精度问题)
const double EPS = 1e-5;
double search(const double *a,int n)
{
double l=0, r=n-1,mid=0,ans=0;
while (r-l>=EPS)
{
if (check(mid)) =mid;
else l=mid;
}
return r;
}