点击获取原题链接
数据结构上机实验之二分查找
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
在一个递增的序列里,查找元素是否存在,若存在输出YES,不存在输出NO.
Input
本题多组数据,首先输入一个数字n(n>=100000),然后输入n个数,数据保证数列递增,然后再输入一个查找数字。
Output
若存在输出YES,不存在输出NO.
Example Input
4
1 3 5 8
3
Example Output
YES
Hint
Author
cz
/*************二分查找时间复杂度O(log_2(N))********/
/////纯STL水过
#include <bits/stdc++.h>
using namespace std;
int a[1000000];
int main()
{
int t;
while(cin>>t)
{
for(int i=0;i<t;i++)///输入数组数据
{
cin>>a[i];
}
int key;///关键字
cin>>key;
int n=find(a,a+t,key)-a;///如果查找成功则返回数据的迭代器(相当与指针)否则返回数字第一个越界元素的迭代器
if(n==t+1)
{
cout<<"NO\n";
}
else cout<<"YES\n";
}
}
/*****手写二分*******/
#include <bits/stdc++.h>
using namespace std;
int a[1000000];
int f(int left,int right,int key)
{
while(left<=right)
{
int mid=(left+right)/2;
if(a[mid]==key)return key;
else if(a[mid]>key)right=mid-1;
else left=mid+1;
}
return -1;
}
int main()
{
int t;
while(cin>>t)
{
for(int i=0;i<t;i++)///输入数组数据
{
cin>>a[i];
}
int key;///关键字
cin>>key;
int n=f(0,t-1,key);///手写二分
if(n==-1)
{
cout<<"NO\n";
}
else cout<<"YES\n";
}
return 0;
}