#include<stdio.h>
#define N 10//定义N的长度为10
/*
折半查找:输入一个数在数组中进行折半查找。
*/
int main()
{
int a[N]={1,12,15,41,55,88,89,90,96,97};
int x,mid,top,bot;//定义X为从键盘中获取的数字,mid为位于中间的下标,top为首元素下标,bot为末元素下标
scanf("%d",&x);//从键盘中获取数字
top=0;
bot=N-1;
do //do-while 功能:先循环再判断
{
mid = (top + bot) / 2;
if(a[mid]==x) //查找的值恰好为a[mid]的值
break;
else if(a[mid]>x) //若输入的值小于a[mid]的值则末端的下标值变为mid下标-1;
bot = mid-1;
else 若输入的值大于a[mid]的值则首端的下标值变为mid下标+1;
top=mid+1;
}while(top<=bot);
if(top<=bot)
printf("a[%d] is %d",mid,x);
else
printf("%d no found",x); //若(bot<top)则说明该数组中不存在;
return 0;
}
折半查找法
最新推荐文章于 2024-05-20 20:08:58 发布