数据结构上机实验之二分查找
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
#include <iostream>
#include<stdio.h>
using namespace std;
int n,a[1000001];
int fin(int i,int j,int k)
{
int low=i;int high=j;int mid;
if(low<=high)
{
mid=low +(high-low)/2;
if(a[mid]>k)
return fin(low,mid-1,k);
else if(a[mid]<k)
return fin(mid+1,high,k);
else return mid;
}
else return -1;
return 0;
}
int main()
{while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
cin>>a[i];
int key;
cin>>key;
int t=fin(0,n-1,key);
if(t==-1)cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
return 0;
}
Source
cz