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

相关推荐
pursuit_csdn20 分钟前
LeetCode 1461. Check If a String Contains All Binary Codes of Size K
算法·leetcode·职场和发展
Crazy________1 小时前
力扣113个mysql简单题解析(包含plus题目)
mysql·算法·leetcode·职场和发展
生成论实验室1 小时前
即事经智能:一种基于生成易算的通用智能新范式(书)
人工智能·神经网络·算法·架构·信息与通信
YxVoyager1 小时前
基于 X-Macro 宏的手动 RTTI 实现模式
c++
清风20221 小时前
vllm 采样调研
人工智能·算法·机器学习
初次攀爬者2 小时前
力扣解题-无重复字符的最长子串
后端·算法·leetcode
MekoLi292 小时前
生成式推荐系统:从“判别式匹配”到“生成式创造”的范式革命
后端·算法
SoulruiA2 小时前
超容易理解+模版套路解决LeetCode 前序+中序、中序+后序、前序+后序遍历构造树问题
java·算法·力扣
wanderist.2 小时前
算法模板-线段树
c++·算法
lcj25112 小时前
蓝桥杯C++梳理(1):从入门到数组
c++·算法