/***********************************
*二分查找:使用于有序排列的集合体
*data:2017.8.17
*Author:shi
**********************************/
#include
int data_serch(int arry[],int left,int right,int data)
{
int mid;
mid = (right/2) - 1;//中间元素的下标
while(left <= right){//当左界限大于右界限时,表明已查找完毕
if(data > arry[mid]){
left = mid+1;//左界限移动到上次中间的地方,即中间值下标值+1
mid = (left + right)/2;//中间值下标也要变化
}else if(data < arry[mid]){
right = mid-1;
mid = (left + right)/2;
}else
return mid;//返回中间值的下标
}
return -1;//当没有这个数字的时候返回
}
int main(void)
{
int arry[11] = {1,2,3,4,5,6,7,8,9,10,11};
int right = 0;
int left = 0;
int data,ret;
printf("输入要查找的数: ");
scanf("%d",&data);
right = sizeof(arry)/sizeof(arry[0]);//求得总共有多少个元素
ret = data_serch(arry,left,right,data);
if(ret < 0)
printf("No such number\n");
if(ret >= 0)
printf("在第%d个位置\n",ret+1);
return 0;
}