二分查找也叫折半查找。
#include<stdio.h>
int search(int arr[],int key,int left,int right)
{
while(left<=right)
{
while(left<=right)
{
int mid=(right+left)/2;
if(arr[mid]<key)
{
left=mid+1;
}
else if(arr[mid]>key)
{
right=mid-1;
}
else
{
return mid;
}
}
return -1;
}
}
int main()
{
int arr[]={0,1,2,3,4,5,6,7,8,9};
int key;
int left=0;
int ret=0;
int right=sizeof(arr)/sizeof(arr[0])-1;
scanf("%d",&key);
ret=search(arr,key,left,right);
if(ret==-1)
{
printf("找不着\n");
}
else
{
printf("%d\n",ret);
}
system("pause");
return 0;
}