折半查找只能用于有序数组中,如果是无序的则不能用此方法。
#include<stdio.h>
int main()
{
int arr[]={0,1,2,3,4,5,6,7,8,9};
int num, mid;
int left=0;
int right=sizeof(arr)/sizeof(arr[0])-1;
printf("请输入要查找的数字>");
scanf("%d",&num);
while(left<=right)
{ mid=(left+right)>>1;
if(num>arr[mid])
left=mid+1;
else if(num<arr[mid])
right=mid-1;
else
break;
}
if(left<=right)
printf("找到了,下标是:%d\n",mid);
else
printf("找不到,-1\n");
return 0;
}