#include <stdio.h>
int BinarySearch(int a[],int x,int n)//查找x在数组中的位置
{
int L,R,mid;
L=0,R=n-1;
while(L<=R)
{
mid=(L+R)/2;//防止溢出可修改为:mid=L+(R-L)/2;
if(a[mid]==x)
return mid;
if(a[mid]<x)
L=mid+1;
else
R=mid-1;
}
return -1;
}
int main()
{
int a[6]={1,2,3,6,7,8};
printf("数字3的下标为:%d\n",BinarySearch(a,3,6));
return 0;
}
运行:
数字3的下标为:2
--------------------------------
Process exited with return value 0
Press any key to continue . . .