C语言版:
#include<stdio.h>
int BinarySearch(int *arr,int left,int right,int elem)
{
int min=left,max=right,mid;
while(min<max-1)
{
mid=min+(max-min)/2;
if(arr[mid]<=elem)
{
min=mid;
}else
{
max=mid;
}
}
if (arr[max]==elem)
{
return max;
}
else if(arr[min]==elem)
{
return min;
}else
{
return -1;
}
}
int BinarySearch2(int *arr,int left,int right,int elem)
{
int min=left,max=right,mid;
int p=-1;
while(min<=max)
{
mid=min+(max-min)/2;
if(arr[mid]<elem)
{
min=mid+1;
}else if(arr[mid]>elem)
{
max=mid-1;
}else
{
p=mid;
break;
}
}
return p;
}
int main()
{
int arr[]={1,3,4,4,6,6,8,8,8,9,12,18};
int n=12;
int t=BinarySearch2(arr,0,n-1,9);
printf("%d\n",t);
return 0;
}