【算法1-6】二分查找与二分答案
#include<cstdio>
using namespace std;
int a[1000009];
int lb(int a[],int l,int r,int key)
{
int ans=-1;
int mid;
while(l<=r)
{
mid=((r-l)>>1)+l;
if(a[mid]==key)//如果查到,保存答案,并尝试继续向前查找
{
ans=mid;
r=mid-1;
}
else if (a[mid]>key)//向左边查找
{
r=mid-1;
}
else //向右边查找
{
l=mid+1;
}
}
return ans;
}
int main()
{
int n,m;
scanf("%d %d",&n,&m);
for (int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for (int i=1;i<=m;i++)
{
int key;
scanf("%d",&key);
printf("%d ",lb(a,1,n,key));
}
}