#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<memory.h>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#define mem(array) memset((array),0,sizeof((array)))
#define Qsort(array,len,cmp) qsort(array,len,sizeof(array[0]),cmp)
#define inf 0x7fffffff
#define MAXN 10+100
using namespace std;
int binarySearch(int* a, int n, int x, int flag = -1)
{ /**
binarySearch parameter description:
int * a a is an array that sorted from small to large
int n n is the length of array a
int x x is the search object
int flag flag is a return sign.
the function will return the index of the first object that equal to the value of object x if the object exists.
when the object is not exist, the function will return -1 while flag is -1,
or return the index of the last maximal object that less than the value of object x.
從長度爲n、已經從小到大排序好的數組a中查找值x的位置,
若存在,返回第一個等於x值的下標,否則返回-1(flag=-1時)或者比x小的最後面一個最大的值(flag!=-1)
*/
if(x < a[0])
return -1;
if(x > a[n-1])
if(flag == -1)
return -1;
else
return n-1;
int l = 0;
int r = n-1;
int mid;
bool getAns = false;
while(l <= r){
mid = (l+r)>>1;
if(x == a[mid]) {getAns = true; break;}
if(x < a[mid]) {r = mid-1; continue;}
if(x > a[mid]) {l = mid+1; continue;}
}
if(getAns){
while(mid >= 0 && x == a[mid])
--mid;
return mid+1;
}
else{
if(flag == -1)
return -1;
else
return r;
}
}
/** refer to the following call*/
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",tdout);
int ans;
int x;
int a[MAXN];
for(int i = 0; i < MAXN; ++i)
a[i] = i<<1;
for(int i = 0; i < MAXN; ++i)
printf("%d ",a[i]);
cout<<endl;
while(cin>>x){
ans = binarySearch(a,MAXN,x,1);
cout << ans <<endl;
}
return 0;
}
C++ 二分查找 binary search 模板
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.