二分查找
Time Limit: 1000MS Memory Limit: 65536KB
Problem Description
在一个递增的序列里,查找元素是否存在,若存在输出YES,不存在输出NO.
Input
本题多组数据,首先输入一个数字n(n>=100000),然后输入n个数,数据保证数列递增,然后再输入一个查找数字。
Output
若存在输出YES,不存在输出NO.
Example Input
4 1 3 5 8 3
Example Output
YES
代码如下:
#include<stdio.h>
int binsearch(int a[],int low,int high,int x)
{
while(low<=high)
{
int mid=(low+high)/2;
if(a[mid]==x) return 1;
else if(a[mid]>x) high=mid-1;
else low=mid+1;
}
return 0;
}
int main()
{
int n,i,x,a[100001],f;
while(~scanf("%d",&n))
{
for(i=0; i<n; i++)
scanf("%d",&a[i]);
scanf("%d",&x);
f=binsearch(a,0,n-1,x);
if(f==1)
printf("YES\n");
else printf("NO\n");
}
return 0;
}