二分的原理其实很简单
复习一下c++ STL库
lower_bound upper_bound :利用二分查找的方法在一个排好序的数组中进行查找
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,找到返回该数字的地址,不存在则返回end。通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
所以这两个函数还需要进一步判断以确定是否存在num
binary_search(起始地址,结束地址,要查找的数值) 返回的是是否存在这么一个数,是一个bool值
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int num[6]={1,2,4,7,15,34};
sort(num,num+6);
int pos1=lower_bound(num,num+6,7)-num; ////返回数组中第一个大于或等于被查数的下标
int pos2=upper_bound(num,num+6,7)-num; //返回数组中第一个大于被查数的下标
cout<<pos1<<endl;
cout<<pos2<<endl;
return 0;
}
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
v.push_back(6);
int pos=lower_bound(v.begin(),v.end(),3)-v.begin();
cout<<pos<<endl;
return 0;
}
这种一般会先确定所需的精度 eps,以 l + eps < r 为循环条件
精度不易确定,固定循环次数(精度通常更高)
原文:https://www.cnblogs.com/serendipity-my/p/12775977.html