用lower_bound函数实现二分搜索

1. lower_bound和upper_bound

定义:假定一个长度为n的单调不下降a0,…,an-1数组和一个数k,lower_bound以二分查找的形式,找出ai>=k的最小地址。

二分搜索的时间复杂度为O(logn).

    #include"algorithm"  //std::lower_bound
    
	lower_bound(begin,end,num)二分查找第一个大于或等于num的数字,找到返回该数字的**地址**,不存在则返回end。
	upper_bound(begin,end,num)二分查找第一个大于num的数字,找到返回该数字的**地址**,不存在则返回end。
	
	lower_bound(begin,end,num,comp)其中comp函数限制了二分查找是**大于等于**换是**小于等于**
	upper_bound(begin,end,num,comp)其中comp函数限制了二分查找是**大于**换是**小于**
	
    lower_bound(begin,end,num)-begin 返回的便是对应数字的数组下标

举个栗子:

#include"iostream"
#include"stdlib.h"
#include"algorithm"   
#include"functional"   // std::greater()
using namespace std;
int main() {
	int a[5] = { 3,1,5,9,7 };
	//由小到大的排序
	sort(a, a + 5, less<int>());
	for (int i = 0; i <= 4; i++)  
		cout << a[i];
	//求第一个小于等于7的数的下标
	cout << endl << lower_bound(a, a + 5, 7, greater<int>()) - a << endl;
	cout << upper_bound(a, a + 5, 7, greater<int>()) - a << endl;
	//求第一个大于等于7的数的下标
	cout << lower_bound(a, a + 5, 7, less<int>()) - a << endl;
	cout << upper_bound(a, a + 5, 7, less<int>()) - a << endl;
	cout << lower_bound(a, a + 5, 7) - a << endl;
	cout << upper_bound(a, a + 5, 7) - a;
	system("pause");
}

此程序的结果为
在这里插入图片描述


2. upper_bound() - lower_bound()

用来判断数组中是否存有某个数

举个栗子:

int a[5] = { 5,3,1,9,7 };
upper_bound(a, a + 5, 3) - lower_bound(a, a + 5, 3)
  • 当数组中存在3,upper_bound()返回3之后一个数的位置,lower_bound()返回3的位置,相减得1
  • 当数组中不存在3,则upper_bound()和lower_bound()均指向3之后一个数的位置,相减得0
#include"iostream"
#include"algorithm"
#include"stdlib.h"
using namespace std;

int main() {
	int a[5] = { 5,3,1,9,7 };
	sort(a, a + 5);
	cout << upper_bound(a, a + 5, 3) - lower_bound(a, a + 5, 3) << endl;
	cout << upper_bound(a, a + 5, 4) - lower_bound(a, a + 5, 4) << endl;
	system("pause");
}

此程序结果:
在这里插入图片描述

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值