1、適用於無重複數的版本
二分查找要求數組有序,時間複雜度爲O(lgn)。適用於無重複數的版本如下:
#include<iostream>
using namespace std;
int biSearch(int a[], int n, int key)
{//非遞歸
int low=0, high=n-1, mid;
while(low<=high)
{
mid=low+(high-low)/2;
if(a[mid]==key)
return mid;
else if(a[mid]>key)
high=mid-1;
else
low=mid+1;
}
return -1;
}
int biSearchRecursion(int a[], int low, int high, int key)
{//遞歸
if(low>high)
return -1;
int mid=low+(high-low)/2;
if(a[mid]==key)
return mid;
else if(a[mid]>key)
return biSearchRecursion(a, low, mid-1, key);
else
return biSearchRecursion(a, mid+1, high, key);
}
int main()
{
int a[]={1,2,3,4,5,6};
int n=sizeof(a)/sizeof(a[0]);
cout<<biSearch(a, n, 3)<<endl;
cout<<biSearchRecursion(a,0,n-1,2)<<endl;
return 0;
}
如上所示代碼都是適用於無重複數的數組,對於有重複數key的數組,給出的位置則是其中的一個,而不是精確定位到上界或者下界,那麼這時需要做些改變。
2、適用於有重複數的版本
1.STL版本:lower_bound(),upper_bound()
ForwardIter lower_bound(ForwardIter first, ForwardIter
last,const _Tp& val)算法返回一個非遞減序列[first, last)中的第一
個大於等於值val的位置。
ForwardIter upper_bound(ForwardIter first, ForwardIter
last, const _Tp& val)算法返回一個非遞減序列[first, last)中第一
個大於val的位置。
如果元素只出現一次,那麼lower_bound()找到這個元素的地址,但是upper_bound()找到的卻是它的下一個;
如果相同元素出現了多次,那麼lower_bound()找到了第一個所找元素的地址,但是upper_bound()找到的卻是最後一個元素的下一個元素的地址。前閉後開!!!!
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int a[]={1,2,3,3,3,4,5,6};
int n=sizeof(a)/sizeof(a[0]);
//cout<<biSearch(a, n, 3)<<endl;
//cout<<biSearchRecursion(a,0,n-1,2)<<endl;
cout<<lower_bound(a,a+n,3)<<endl;//地址:0x28feec
cout<<upper_bound(a,a+n,3)<<endl;//地址:0x28fef8
////減去首地址,就找到了下標位置
cout<<lower_bound(a,a+n,3)-a<<endl;//2,第一個出現的位置
cout<<upper_bound(a,a+n,3)-a<<endl;//5!!!最後一個的下一位置
return 0;
}
2.
class Solution {
public:
int GetNumberOfK(vector<int> data ,int k) {
int n=data.size();
if(n==0) return 0;
int first=GetFirstK(data,k,0,n-1);
int last=GetLastK(data,k,0,n-1);
int num=0;
if(first>-1 && last>-1)
num = last-first+1;
return num;
}
int GetFirstK(vector<int> &a, int k, int start, int end)
{//至少包含一個k則返回第一個的下標
if(start > end) return -1;//不包含k則返回-1
int mid=start + (end-start)/2;
if(a[mid]==k){
if((mid>0&&a[mid-1]!=k) || mid==0)
return mid;
else
end=mid-1;
}
else if(a[mid]<k)
start=mid+1;
else
end=mid-1;
return GetFirstK(a, k, start, end);
}
int GetLastK(vector<int> &a, int k, int start, int end)
{//至少包含一個k則返回最後一個的下標
if(start > end) return -1;//不包含k則返回-1
int mid=start + (end-start)/2;
if(a[mid]==k){
if((mid<a.size()-1&&a[mid+1]!=k) || mid==a.size()-1)
return mid;
else
start=mid+1;
}
else if(a[mid]<k)
start=mid+1;
else
end=mid-1;
return GetLastK(a, k, start, end);
}
};