#include<iostream>
using namespace std;
int a(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 b(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 c(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 d(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;
}
void printArray(int array[],int arrLen)
{
for (int i=0;i<arrLen;++i)
{
cout<<array[i]<< " ";
}
cout << endl;
}
int main()
{
int arr[]={1,2,2,3,3,5,6,9};
int arrayLen=sizeof(arr)/sizeof(int);
printArray(arr,arrayLen);
cout<<"第一个2的位置:"<<a(2,arr,arrayLen)<<endl;
cout<<"最后一个2的位置:"<<b(2,arr,arrayLen)<<endl;
cout<<"第一个大于等于4的位置:"<<c(4,arr,arrayLen)<<endl;
cout<<"最后一个小于等于4的位置:"<<d(4,arr,arrayLen)<<endl;
return 0;
}