利用二分搜索,查找一个给定的值所在区间
来源:互联网 发布:华讯软件 编辑:程序博客网 时间:2024/06/05 16:34
#include <iostream>#include <algorithm>#include <cstdio>#include <cstdlib>#include <functional>using namespace std;//区间定义struct Node { int start; int end; };bool operator < (const Node & l,const Node &r){ return (l.start<r.start);}int bin_search_in_arrang(Node * a,const int &n,const int & key);int main(){ int n; int key; int pos; int test; Node * ptr=NULL; cin>>test;//获取测试用例数目 cin>>n;//获取n个区间 cin>>key;//获取待查找的元素 while(test--) { ptr=new Node [n]; for(int i=0;i!=n;++i) { cin>>ptr[i].start>>ptr[i].end; } less<Node> l; sort(ptr,ptr+n,l); if((pos=bin_search_in_arrang(ptr,n,key))==-1) cout<<"can not find"<<endl; else cout<<"The element is at "<<pos+1<<endl; delete [] ptr; }return 0;}//该二分查找在多个区间中查找给定值在哪一个区间中。//如果给定值位于多个目标区间中,那么返回的是任意的一个区间下标。//函数不知道是否写对了。int bin_search_in_arrang(Node * a,const int &n,const int & key){ int low=0; int high=n-1; int mid; while(low<=high) { mid=(low+high)/2; if(key<a[mid].end) { if(key>=a[mid].start) return mid; else high=mid-1; } else { if(key>a[mid].end) low=mid+1; else return mid; } } return -1;}