二分法查找,也称为折半法,是一种在有序数组中查找特定元素的搜索算法。
#include<stdio.h>
int find(int a[],int e,int size)
{
int mid;
int det=-1,left=0,right = size-1;//c语言数组下标-1
while(left<right)
{
mid=(left+right)/2;
if(e>a[mid]){
left=mid+1;
}else if(e<a[mid]){
right=mid-1;
}else{
det=mid;
return printf("%d在数组第%d位置\n",e,det+1);
}
}
if(a[left]==e)
{
printf("%d在数组第%d位置\n",e,left+1);
}else {
printf("没有此值");
}
}
main()
{
int aim = 59; //所要查找的数值
int a[]={1,2,3,4,5,7,999};
find(a,aim,7);//7是数组长度
}
运行的结果如下
没有此值
Process exited after 0.1509 seconds with return value 0
请按任意键继续. . .