#include<stdio.h>
#include<stdlib.h>
int BinSearch(int a[],int size,int m);
int main()
{
int n;
int a[1000];
printf("请输入元素个数:\n");
scanf("%d",&n);
int i;
printf("请输入各个元素:\n");
for(i=0;i<n;++i)
scanf("%d",&a[i]);
int m;
printf("请输入要查询元素:\n");
while(~scanf("%d",&m))
{
if(BinSearch(a,n,m)!=-1)
printf("要查询元素位置是:%d\n",BinSearch(a,n,m)+1);
else
printf("查询失败!\n") ;
//printf("%d###\n",BinSearch(a,n,m));
}
return 0;
}
int BinSearch(int a[],int size,int m)
{
int low,high,mid;
low=0;
high=size-1;
while(low<=high)
{
mid=(low+high)/2;//printf("%d##\n",a[mid]);
if(m==a[mid])return mid;
else if(m>a[mid])
low=mid+1;
else
high=mid-1;
}
return -1;
}
03-27