1508: 二分查找
Description
给定一个有序整数集合s(从小到大),集合中有n个元素,我有m次询问,对于每次询问给定一个整数x,若 x存在于集合s中输出x found at y,y为集合s中出现x的下标,否则输出x not found.
Input
第一行为两个正整数n,m.(1<=n,m<=100000)代表集合中元素的个数和查询次数,接下来一行有n个正整数代表集合里的元素.接下来一行有m个正整数代表查询的元素.
Output
详见sample output
Sample Input
7 3
1 2 4 7 9 10 13
2 3 7
Sample Output
2 found at 2
3 not found
7 found at 4
HINT
简单的二分查找
Code:
#include<stdio.h>
int main()
{
int n,m;
int a[100005],x;
scanf("%d %d",&n,&m);
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
while(m--)
{
scanf("%d",&x);
int count=0,i=0,j=n-1;
int mid,f=0;
while(i<=j)
{
count++;
mid=(i+j)/2;
if(x==a[mid])
{
printf("%d found at %d\n",x,mid+1);
f=1;
break;
}
if(x>a[mid])
i=mid+1;
if(x<a[mid])
j=mid-1;
}
if(!f)
printf("%d not found\n",x);
}
return 0;
}