基础知识:
low_bound查找大于或等于x的第一个位置
二分查找法(适用于非降序排列)
*lower_bound函数:有三个参数,返回一个地址
1.数组的一个地址(一般是首地址,也可以是待查询的“首地址”);
2.数组的的一个地址(待查找区间的尾地址)
3.待查找的元素
*lower_upper与上相似,但查找的是大于x的第一个地址
书上的代码:
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=10000;
int main(){
int n,q,x,a[maxn],kase=0;
while(scanf("%d%d",&n,&q)==2&&n){
printf("CASE# %d:\n",++kase);
for(int i=0;i<n;i++) scanf("%d",&a[i]);
sort(a,a+n);
while(q--){
scanf("%d",&x);
int p=lower_bound(a,a+n,x)-a; //在已排序数组 a中寻找x;
if(a[p]==x) printf("%d found at %d\n",x,p+1);
else printf("%d not found\n",x);
}
}
return 0;
}