您的位置:首页 > 理论基础 > 数据结构算法

数据结构上机实验之二分查找

2018-03-16 23:39 393 查看

数据结构上机实验之二分查找

Time Limit: 1000 ms Memory Limit: 65536 KiB[align=center]Submit Statistic Discuss[/align]

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
,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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: