//用二分法查找数组中元素
#include<stdio.h>
#include<stdlib.h>
#define N 15
int main()
{
int arr[N]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int low=0; //记录下标
int high=N-1;
int middle;
int value; //需要查找的数
int flag;
printf("输入要查找数据:");
scanf("%d",&value);
if(value<arr[0]&&value>arr[N-1])
printf("输入的数据非法\n");
else
while(low<=high)
{
middle=(low+high)/2;
if(arr[middle]<value) //左侧数据去掉
low=middle+1;
else if(arr[middle]==value)
{
flag=middle;
break;
}
else if(arr[middle]>value) //右侧去掉
high=middle-1;
else
flag=-1;
}
if(flag==-1)
printf("没有找到要找的数据\n");
else
printf("要找的数据是arr[%d]=%d\n",flag,arr[flag]);
return 0;
}