- BinarySearch(int a[],int n,int p); //有序数组,二分查找p
- LowerBound(int a[],int n,int p); //升序数组,找比p小的最大数
注意:
int mid=(L+R)/2;
为了防 (L+R) 过大溢出,最好写成:
int mid=L+(R-L)/2;
int mid=(L+R)/2;
为了防 (L+R) 过大溢出,最好写成:
int mid=L+(R-L)/2;
#include <iostream>
#include <cmath>
using namespace std;
int BInarySearch(int a[],int n,int p)
{
int L=0;
int R=n-1;
while(L<=R)
{
int mid=L+(R-L)/2;
if(a[mid]==p)
return mid;
else if(a[mid]>p)
R=mid-1;
else
L=mid+1;
}
return -1;
}
int LowerBound(int a[],int n,int p)
{
int L=0;
int R=n-1;
int lastPos=-1;
while(L<=R)
{
int mid=L+(R-L)/2;
if(a[mid]>=p)
R=mid-1;
else
{
lastPos=mid;
L=mid+1;
}
}
return lastPos;
}
int main()
{
int a[10]={0,1,2,3,4,5,6,7,8,9};
cout<<BInarySearch(a,10,5)<<endl;
cout<<LowerBound(a,10,5)<<endl;
return 0;
}