线性搜索
int linerSearch(int a[],int n,int key){
for(int i=0; i<n;i++)
{
if (a[i]==key)return i;
}
return -1;
}
二分搜索
int binarySearch(int a[],int n,int key){
int low = 0,high = n,mid;
while(low<high){
mid = (low+high)>>1;
if(a[mid]==key)return mid;
else if (a[mid]<key)low=mid+1;
else high = low - 1;
}
return -1;
}
STL
lower_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于或等于num的数字,
找到返回该数字的地址,不存在则返回end。
通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
int low=lower_bound(t.begin(),t.end(),5)-t.begin();
int upp=upper_bound(t.begin(),t.end(),5)-t.begin();
upper_bound( begin,end,num):从数组的begin位置到end-1位置二分查找第一个大于num的数字,
找到返回该数字的地址,不存在则返回end。
通过返回的地址减去起始地址begin,得到找到数字在数组中的下标。
main
int main()
{
int a[]={12,263,234,1,23,523,54,481,128};
int n= sizeof(a)/sizeof(int);
int key = 523;
cout<<linerSearch(a,n,key)<<endl;
sort(a,a+n);
cout<<binarySearch(a,n,key)<<endl;
cout<<lower_bound(a,a+n,key)-a<<endl;
cout<<upper_bound(a,a+n,key)-a<<endl;
}
输出结果
5
8
8
9