数据结构上机实验之二分查找
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
在一个递增的序列里,查找元素是否存在,若存在输出YES,不存在输出NO.
Input
本题多组数据,首先输入一个数字n(n>=100000),然后输入n个数,数据保证数列递增,然后再输入一个查找数字。
Output
若存在输出YES,不存在输出NO.
Sample Input
4 1 3 5 8 3
Sample Output
YES
Hint
Source
cz
#include <bits/stdc++.h>
using namespace std;
const int N=3000000;
int a[N],flag;
int f(int low,int high,int x)
{
if(low<=high)
{
int mid=(high+low)/2;
if(a[mid]>x)
return f(low,mid-1,x);
if(a[mid]<x)
return f(mid+1,high,x);
else
{return 1;}
}
return 0;
}
int main()
{
int n,x;
while(scanf("%d",&n)!=EOF)
{
flag=0;
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
scanf("%d",&x);
flag=f(0,n-1,x);
if(flag==1)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}