二分查找--C++实现

1. 简介

满足有序性,每次排除一半的可能性。

2. 实现

2.1 手写
cpp 复制代码
int bin_search(vector<int> &arr,int v) {
	int hi = arr.size() - 1;
	int lo = 0;
	
	while ( lo <= hi)
	{
		int mid = (lo + hi) >> 1;
		if (arr[mid] < v)
			lo = mid + 1;
		else
			hi = mid - 1;
	}
	return hi;
}
2.2 STL
  1. lower_bound()
    C++20之后才有
    找到第一不小于某个值的位置
  • 使用
cpp 复制代码
lower_bound(potions.begin(), potions.end(), tar);
  • 实现
cpp 复制代码
template<class ForwardIt, class T>
ForwardIt lower_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 (*it < value)
        {
            first = ++it; 
            count -= step + 1; 
        }
        else
            count = step;
    }
 
    return first;
}
  1. upper_bound()
    找到第一个严格大于某个值的位置
    C++20之后才能用。
  • 使用
cpp 复制代码
upper_bound(potions.begin(), potions.end(), tar);
  • 实现
cpp 复制代码
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;
}

3. Ref

cppreference

相关推荐
ghie90909 小时前
图像去雾算法详解与MATLAB实现
开发语言·算法·matlab
云泽8089 小时前
从三路快排到内省排序:探索工业级排序算法的演进
算法·排序算法
qwepoilkjasd10 小时前
C++智能指针介绍
c++
weixin_4684668510 小时前
遗传算法求解TSP旅行商问题python代码实战
python·算法·算法优化·遗传算法·旅行商问题·智能优化·np问题
·白小白10 小时前
力扣(LeetCode) ——43.字符串相乘(C++)
c++·leetcode
咬_咬10 小时前
C++仿muduo库高并发服务器项目:Poller模块
服务器·开发语言·c++·epoll·muduo
FMRbpm11 小时前
链表5--------删除
数据结构·c++·算法·链表·新手入门
程序员buddha11 小时前
C语言操作符详解
java·c语言·算法
John_Rey11 小时前
API 设计哲学:构建健壮、易用且符合惯用语的 Rust 库
网络·算法·rust
愿没error的x11 小时前
动态规划、贪心算法与分治算法:深入解析与比较
算法·贪心算法·动态规划