有序向量二分法查找
# include <iostream>
#include <vector>
using namespace std;
//[lr)
template <typename T>
int binarySearch_R(vector<T> L,T elem){
int l=0,mid,r=L.size();
while(l<r){
mid=(l+r)>>1;
if(elem<L[mid]) r=mid;
else l=mid+1;
}
return l-1;//返回的位置(l-1)表示小于等于elem的最后一个元素位置'
}
template <typename T>
int binarySearch_L(vector<T> L,T elem){
int l=0,mid,r=L.size();
while(l<r){
mid=(l+r)>>1;
if(L[mid]<elem) l=mid+1;
else r=mid;
}
return l;//l表示大于等于elem的最小的元素位置
}
int main(){
int list[]={1,2,3,4,5,6,7,7,7,9,10,11};
vector<int> L;
int length=sizeof(list)/sizeof(int);
for (int i=0;i<length;i++){
L.push_back(list[i]);
cout<<L[i]<<" ";
}
cout<<endl;
int x=7;
cout<<"x="<<x<<endl;
int result=binarySearch_L(L,x);
cout<<"rank="<<result<<","<<list[result]<<endl;
}