二分查找函数
- lower_bound(起始地址,结束地址,要查找的数值)
返回第一个大于等于所要查找的元素的地址
适合求一个数组里比该数小的个数 - upper_bound(起始地址,结束地址,要查找的数值)
返回第一个大于所要查找的元素的地址
适合求一个数组里比该个数大的个数
代码
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
int n,x,a[100];
scanf("%d",&n);
for(int i=0;i<n;i++)scanf("%d",&a[i]);//数组从0开始
sort(a,a+n);//二分 数组一定要有序
scanf("%d",&x);
int pos1=lower_bound(a,a+n,x)-a;//返回第一个大于等于所要查找的元素的地址
int num1=pos1;//数组里比该数小的个数
int pos2=upper_bound(a,a+n,x)-a;//返回第一个大于所要查找的元素的地址
int num2=n-pos2;//数组里比该数大的个数
printf("%d %d \n",num1,num2);
return 0;
}