今天有童鞋问到我二分的题,一时间竟然忘了二分怎么敲了。。(就特么你这记性还是别搞ACM了)宇似乎又敲了一遍来温习一下(其实就是存个档怕以后真的彻底忘了
)
二分的思想:在一个升序的序列中查找一个元素,普通的想法是直接从头撸到尾然后判断,但是当数据很多的时候这中普通的思想绝壁会超时(不过不要小看这种普通的从头到尾去遍历的思想,有的时候,它很暴力)二分不同,它是每次去把带查找元素,假设是x,与序列中间位置的数f[mid]比较,如果x比f[mid]大 ,说明x肯定在mid+1--high之间,然后就缩小范围,在mid+1--high之间查找x,反之亦然。复杂度好像是O(logn)的样子
#include <stdio.h>
#include <iostream>
using namespace std;
int f[100]; //待查找数组,假设已按升序排序
int binsrch1(int low,int high,int x) //非递归查找
{
int mid;
while(low<=high)
{
mid=(low+high)/2;
if(f[mid]==x)
return mid;
if(f[mid]>x)
high=mid-1;
if(f[mid]<x)
low=mid+1;
}
return -1;
}
int binsrch2(int low,int high,int x) //递归查找
{
int mid;
if(low>high)
return -1;
mid=(low+high)/2;
if(x==f[mid])
return mid;
else if(x<f[mid])
binsrch2(low,mid-1,x);
else if(x>f[mid])
binsrch2(mid+1,high,x);
}
int main()
{
int i,x;
for(i=0;i<10;i++)
cin>>f[i];
cin>>x;
cout<<binsrch1(0,9,x)<<endl;
cout<<binsrch2(0,9,x)<<endl;
return 0;
}
下面用 标准库来取代二分
binary_search试图在已排序的[first, last)中寻找元素value。如果[first, last)内有等价于value的元素,它会返回true,否则返回false,它不返回查找位置。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n,x;
while(cin>>n){
vector <int> s;
while(n--){
cin>>x;
s.push_back(x);
}
cin>>x;
if(binary_search(s.begin(),s.end(),x))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}