折半查找法(二分法)
该方法是查找的范围不断缩小一半,所以查找效率较高
#include<stdio.h>
int main()
{
int arr[]={0,1,2,3,4,5,6,7,8,9};
int left=0;
int right=sizeof(arr)/sizeof(arr[0])-1;
int n=0;
int t=5;
while(left<=right)
{
int mid=left+(right-left)/2;
if(t>arr[mid])
{
left=mid+1;
}
else if(t<arr[mid])
{
right=mid-1;
}
else
{
printf("找到%d了\n",t);
break ;
}
if(left>right)
{
printf("找不到");
}
n=n+1;
}
printf("%d次循环\n",n);
return 0;
}
int main()
{
int arr[]={0,1,2,3,4,5,6,7,8,9};
int left=0;
int right=sizeof(arr)/sizeof(arr[0])-1;
int n=0;
int t=5;
while(left<=right)
{
int mid=left+(right-left)/2;
if(t>arr[mid])
{
left=mid+1;
}
else if(t<arr[mid])
{
right=mid-1;
}
else
{
printf("找到%d了\n",t);
break ;
}
if(left>right)
{
printf("找不到");
}
n=n+1;
}
printf("%d次循环\n",n);
return 0;
}