#include<iostream>
using namespace std;
int binarySearchFirstEqual(int searchKey,int array[],int arrLen)
{
int low=0;
int high=arrLen-1;
int keyPos=-1;
while(low<=high)
{
int mid=low+((high-low+1)>>1);
if(array[mid]>searchKey)
{
high=mid-1;
}
else if(array[mid]<searchKey)
{
low=mid+1;
}
else
{
if(mid==0 || array[mid-1]!=searchKey)
{
keyPos=mid;
break;
}
else
{
high=mid-1;
}
}
}
return keyPos;
}
int binarySearchLastEqual(int searchKey,int array[],int arrLen)
{
int low=0;
int high=arrLen-1;
int keyPos=-1;
while(low<=high)
{
int mid=low+((high-low+1)>>1);
if(array[mid]>searchKey)
{
high=mid-1;
}
else if(array[mid]<searchKey)
{
low=mid+1;
}
else
{
if(mid==arrLen-1 || array[mid+1]!=searchKey)
{
keyPos=mid;
break;
}
else
{
low=mid+1;
}
}
}
return keyPos;
}
int Larger(int searchKey,int array[],int arrLen)
{
int low=0;
int high=arrLen-1;
int keyPos=-1;
while(low<=high)
{
int mid=low+((high-low+1)>>1);
if(array[mid]>=searchKey)
{
if(mid==0 || array[mid-1]<searchKey)
{
keyPos=mid;
break;
}
else
{
high=mid-1;
}
}
else
{
low=mid+1;
}
}
return keyPos;
}
int Smaller(int searchKey,int array[],int arrLen)
{
int low=0;
int high=arrLen-1;
int keyPos=-1;
while(low<=high)
{
int mid=low+((high-low+1)>>1);
if(array[mid]<=searchKey)
{
if(mid==arrLen-1 || array[mid+1]>searchKey)
{
keyPos=mid;
break;
}
else
{
low=mid+1;
}
}
else
{
high=mid-1;
}
}
return keyPos;
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9};
int len=sizeof(arr)/sizeof(int);
cout<<"查找的数字:7"<<endl;
cout<<"binarySearchFirstEqual下标:"<<binarySearchFirstEqual(7,arr,len)<<endl;
cout<<"binarySearchLastEqual下标:"<<binarySearchLastEqual(7,arr,len)<<endl;
cout<<"Larger下标:"<<Larger(7,arr,len)<<endl;
cout<<"Smaller下标:"<<Smaller(7,arr,len)<<endl;
}