1.二分查找的前提
- 库函数只能对数组进行二分查找
- 对一个数组进行二分查找的前提是这个数组中的元素是单调的(一般为单调递减),当然如果单调不增也可以(需要修改比较函数)
2.binary_search函数
- binary_search是C++标准库中的一个算法函数,用于在已排序的序列(例如数组或容器)中查找特定元素
- 它通过二分查找算法来确定序列中是否存在目标元素
- 函数返回一个bool值,表示目标元素是否存在于序列中
- 如果需要获取找到的元素的位置,可以使用std::lower bound函数或std:upper_bound函数
vector<int>numbers={1,3,5,7,9};
int target=5;//这里的target是目标值
//使用binary_search查找目标元素
bool found=binary_search(numbers.begin(),numbers.end(),target)l
if(found){
cout<<"Target element"<<target<<"found."<<"\n";
}//found为true
else{
cout<<"Target element"<<target<<"not found."<<"\n";
}//found为false
3.lower_bound函数和upper_bound函数
- 前提:数组必须为非降序
- 如果要在非升序的数组中使用,可以通过修改比较函数实现(方法与sot自定义比较函数类似)
- lower_bound(st,ed,x)返回地址 [st ed)中第一个大于等于x的元素的地址
- upper_bound(st,ed,x)返回地址[st.ed)中第一个大于x的元素的地址
- 如果不存在则返回最后一个元素的下一个位置,在vector中即end()
vector<int>v={5,6,4,9,13,19};
sort(v.begin(),v.end());
for(auto &i:v){
cout<<i<<' ';
}
cout<<"\n";
//找到数组中第一个大于等于9的元素的位置
cout<<(lower_bound(v.begin(),v.end(),9)-v.begin())<<"\n";
例题:二分查找数组
给定一个数组,其采用如下代码定义:
int data[200];
for(i=0;i<200;i++)data[i]=4*i+6;
先给定某个数(该整数一定在data数组中),请你找出它在数组中的位置
#include<bits/stdc++.h>
using namespace std;
int main(){
int data[200];
for(int i=0;i<200;++i){
data[i]=4*i+6;
}
int target;
cin>>target;
cout<<(lower_bound(data,data+200,target)-data)<<"\n";
return 0;
}