二分查找--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

相关推荐
我叫黑大帅8 分钟前
为什么map查找时间复杂度是O(1)?
后端·算法·面试
炽烈小老头33 分钟前
【每天学习一点算法 2026/04/20】除自身以外数组的乘积
学习·算法
skilllite作者1 小时前
AI agent 的 Assistant Auto LLM Routing 规划的思考
网络·人工智能·算法·rust·openclaw·agentskills
破浪前行·吴2 小时前
数据结构概述
数据结构·学习
香蕉鼠片2 小时前
MFC是什么
c++·mfc
心态与习惯2 小时前
Julia 初探,及与 C++,Java,Python 的比较
java·c++·python·julia·比较
py有趣3 小时前
力扣热门100题之不同路径
算法·leetcode
_日拱一卒3 小时前
LeetCode:25K个一组翻转链表
算法·leetcode·链表
啊哦呃咦唔鱼3 小时前
LeetCodehot100-394 字符串解码
算法
小欣加油3 小时前
leetcode2078 两栋颜色不同且距离最远的房子
数据结构·c++·算法·leetcode·职场和发展