二分查找,实现自定义lower_bound函数、upper_bound函数

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;
}

猜你喜欢

转载自blog.csdn.net/h2017010687/article/details/81709952