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

来源:互联网 发布:php 一键生成工具 编辑:程序博客网 时间:2024/06/03 23:50

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

Time Limit: 1000MSMemory Limit: 65536KB

Problem Description

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

Input

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

Output

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

Example Input

41 3 5 83

Example Output

YES
#include<iostream>#include<cstdio>using namespace std;int find(int a[],int pos,int end,int key){int mid=0;    if(pos<end){     if(a[pos]==key) return pos; else if(a[end]==key) return end; else {     mid=(pos+end)/2; if(a[mid]==key) return mid; else if(a[mid]<key) {     pos=mid+1; find(a,pos,end,key);        //递归 } else  {      end=mid-1;  find(a,pos,end,key); } }} else return -1;}int main(){    int n,key=0;while(scanf_s("%d",&n)!=EOF)       //加上EOF{     int *p=new int[n]; for(int i=0;i<n;i++) scanf_s("%d",&p[i]);       //用scanf() printf()  而不是cin cout scanf_s("%d",&key);int x=find(p,0,n-1,key);if(x==-1)printf("NO\n");elseprintf("YES\n");}return 0;}

原创粉丝点击