二分查詢,實現自定義lower_bound函式、upper_bound函式
阿新 • • 發佈:2018-12-20
lower_bound函式
#include<iostream> #include<algorithm> using namespace std; const int M=1e5; int my_lower_bound(int *a,int n,int x){ int l=0,r=n-1; int m; while(l<r){ m=(l+r)/2; if(a[m]<x) l=m+1; else r=m; } if(a[l]>=x) return l; else return -1; } int main() { int a[M],n,x; cin >> n >> x; for(int i=0;i<n;i++) cin >> a[i] ; sort(a,a+n); cout << my_lower_bound(a,n,x); return 0; }
upper_bound函式
#include<iostream> #include<algorithm> using namespace std; const int M=1e5; int my_upper_bound(int *a,int n,int x){ int l=0,r=n-1; int m; while(l<r){ m=(l+r)/2; if(a[m]<=x) l=m+1; else r=m; } if(a[l]>x) return l; else return n; } int main() { int a[M],n,x; cin >> n >> x; for(int i=0;i<n;i++) cin >> a[i] ; sort(a,a+n); cout << my_upper_bound(a,n,x); return 0; }