数据结构上机实验之二分查找
题目描述
在一个递增的序列里,查找元素是否存在,若存在输出YES,不存在输出NO.
输入
本题多组数据,首先输入一个数字n(n>=100000),然后输入n个数,数据保证数列递增,然后再输入一个查找数字。
输出
若存在输出YES,不存在输出NO.
示例输入
4 1 3 5 8 3
示例输出
YES
#include <iostream> #include<stdio.h> #include<string.h> #include<stdlib.h> #include<math.h> #include<malloc.h> #include<stack> using namespace std; int binary(int a[],int s,int t,int key) { int mid; while(s<t) { mid=(s+t)/2; if(a[mid]==key) return 1; if(a[mid]>key) t=mid-1; else s=mid+1; } return 0; } int main() { int n,a[100001],key; while(scanf("%d",&n)!=EOF) { for(int i=0; i<n; i++) scanf("%d",&a[i]); scanf("%d",&key); int k=binary(a,0,n-1,key); if(k==1) cout<<"YES"<<endl; else cout<<"NO"<<endl; } }