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

来源:互联网 发布:单片机制作电子时钟 编辑:程序博客网 时间:2024/06/05 23:06

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

Time Limit: 1000MSMemory Limit: 65536KB
SubmitStatistic Discuss

Problem Description

 在一个递增的序列里,查找元素是否存在,若存在输出YES,不存在输出NO.

Input

 本题多组数据,首先输入一个数字n(n>=100000),然后输入n个数,数据保证数列递增,然后再输入一个查找数字。

Output

 若存在输出YES,不存在输出NO.

Example Input

41 3 5 83

Example Output

YES

Hint

#include<cstdio>#include<algorithm>using namespace std;int cmp(int a,int b){    return a<b;}int main(){    int n,d;    while(scanf("%d",&n)!=EOF)    {        int num[n];        for(int i=0;i<n;i++)            scanf("%d",&num[i]);        sort(num,num+n,cmp);        scanf("%d",&d);        int low=0,high=n-1,mid;        while(low<=high)        {            mid=(low+high)/2;            if(d<num[mid])                high=mid-1;            if(d>num[mid])                low=mid+1;            if(d==num[mid])                break;        }        if(low>high)            printf("NO\n");        else            printf("YES\n");    }    return 0;}


原创粉丝点击