[STL] 标准二分算法模板 && lower_bound() upper_bound()代码解析

15 篇文章 0 订阅

一、摘要

二分算法是经常使用的算法之一,熟练使用二分算法是一个程序员的基本素养。C++的<algorithm>头文件中存在lower_bound()upper_bound()函数,支持在已排好序的容器中查找首个大于等于或者大于目标元素的迭代器位置。同时在有序容器类,例如set<>和map<>,也存在类似功能的函数。熟练使用lower_bound()upper_bound()函数可以方便地使用二分算法解决问题。本文基于< algorithm>源代码,对lower_bound()upper_bound()代码进行分析解释,对于实现严谨高效的二分算法具有重要参考价值。

本文在第二部分给出<algorithm>头文件中lower_bound()upper_bound()函数的代码,并对代码进行分析解释;第三部分是对二分算法的实现,并注明了实现中需要注意的事项;最后一部分是本文参考文章链接。

二、官方代码

1. lower_bound(first, last, value)

lower_bound(first, last, value)函数根据给定的value值,返回[first, last)范围中第一个大于等于value的迭代器(元素位置)。若无法找到,则返回last,因此实际可供返回的范围为[first,last]。

源代码
template<class ForwardIt, class T>
ForwardIt lower_bound(ForwardIt first, ForwardIt last, const T& value)
{
    ForwardIt it;// 用于表示[first, last)的中间位置值
    // count 表示待搜索的容器中元素个数,初始为last-first
    // step 用来得到待搜索范围的中间位置
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    // distance即计算[first,last)中间的元素个数
    count = std::distance(first, last);
	// 若待搜索的容器中元素个数大于0个,则进入while循环
    while (count > 0) {
        it = first; // (1) 
        step = count / 2;// (2) 求中间位置元素距离first的间隔
        std::advance(it, step);	// (3),这三行用来使it等于[first,last)的中间位置。
        // 例如:若待搜索的容器为{0,1,2,3},那么first指向元素0的位置,last指向3后面的一个位置,count为容器中元素的个数等于4,it指向0+4/2=2,即it指向2;
        // 若待搜索的容器为{0,1,2},那么first指向元素0的位置,last指向3后面的一个位置,count为容器中元素的个数等于3,it指向0+3/2=1,即it指向1;
        // 即若容器中元素个数为奇数,it指向中间位置的元素;若容器中个数为偶数,则it指向中间两个元素中后一个元素。
        if (*it < value) {
		// 若中间元素it小于value,则说明最终需要返回的元素在[it+1,last)范围内
            first = ++it; //则将first赋值为it+1位置处
            count -= step + 1; // 更新现在的搜索范围内的元素个数。count变为count - [first,it]范围内的元素个数,即count -= (step+1)
        }
        else
        // 若中间元素it大于等于value,则说明最终需要返回的元素在[first,it]
        // 因此此时不需要更改first位置,只需要令搜索范围变为[first,it),即count变为step即可;
        // 此处新的搜索范围变为[first,it)而不是[first,it]的原因是,若[first,it)范围内找不到大于等于value的元素,则返回[first,it)范围内最后一个元素(it-1)的下一个元素位置(it)正好可以得到[first,last)范围内第一个大于等于value的位置。
        // 同时,这样设置保证了每次循环的count值都变小。若初始容器为{10,10},value = 5,那么若此处更新使用count=step+1,则会形成死循环。
            count = step;
    }
    // 返回结果第一个大于等于value的元素位置,若没有则first会指向last,即返回last。
    return first;
}

可以将lower_bound()函数理解为一个递归函数,该函数用于求在范围[first, first+count)范围内第一个大于等于value的元素,若不存在返回first+cound,只不过是使用while循环实现。在具体实现中保证了count每次循环都变为原来的一半,因此算法复杂度为log(n)。

2. upper_bound(first, last, value)

upper_bound()函数与lower_bound()函数类似,只不过将判断条件if (*it < value)变为if (!(value < *it)),其他部分都相同,因此对upper_bound()函数不在添加注释。

template<class ForwardIt, class T>
ForwardIt upper_bound(ForwardIt first, ForwardIt last, const T& value)
{
    ForwardIt it;
    typename std::iterator_traits<ForwardIt>::difference_type count, step;
    count = std::distance(first, last);
 
    while (count > 0) {
        it = first; 
        step = count / 2; 
        std::advance(it, step);
        if (!(value < *it)) {
            first = ++it;
            count -= step + 1;
        } 
        else
            count = step;
    }
    return first;
}

三、二分算法实现

1. 二分算法实现

基于第二部分中给出的代码,我们参考其代码结构给出二分算法的实现。
算法需要解决的问题为,给出一个递增数组nums,求数组中第一个大于等于value的值的下标,若不存在则输出“不存在”。
实现代码如下:

#include<iostream>
#include<vector>
using namespace std;
int main(){
	vector<int> nums = {0,1,2,3,4,5,6,7,8,9};
	int value = 5;
	int first = 0;
	int last = nums.size();
	int step;
	int count = last-first;
	int middle;
	while(count>0){
		step = count/2;
		middle = first+step;
		if(nums[middle]<value){
			first = middle+1;
			count = count - (step+1);
		}else{
			count = step;
		}
	}
	if(first<nums.size()){
		cout<<"第一个大于等于"<<value<<"的元素下标为:"<<first<<endl;
	}else{
		cout<<"数组nums中没有大于等于"<<value<<"的元素"<<endl;
	}
	return 0;
}

程序输出为:

第一个大于等于5的元素下标为:5

2. 注意事项

  • 使用二分算法要求数组有序(递增)。若数组递减,可以使用lower_bound(first, last, cmp)函数自定义比较函数。
  • 在while()循环中每次都要使count变为上次循环的一半大小(或者一半减一),不然容易造成死循环。

四、参考

[1]. std::lower_bound
[2]. std::upper_bound

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值