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

相关推荐
滴滴答滴答答29 分钟前
机考刷题之 9 LeetCode 503 下一个更大元素 II
算法·leetcode·职场和发展
飞Link32 分钟前
梯度下降的优化算法中,动量算法和指数加权平均的区别对比
人工智能·深度学习·算法
啊哦呃咦唔鱼41 分钟前
LeetCode hot100-15 三数之和
数据结构·算法·leetcode
_日拱一卒42 分钟前
LeetCode(力扣):杨辉三角||
算法·leetcode·职场和发展
rqtz1 小时前
基于I2C总线的IMU-磁力计融合算法与数据共享
算法·iic·espidf·qmc5883p·icm42670p·imu磁力计融合
leluckys1 小时前
算法-链表-二、成对交换两个节点
数据结构·算法·链表
小糯米6011 小时前
C++ 排序
c++·算法·排序算法
未来之窗软件服务1 小时前
幽冥大陆(一百12)js打造json硬件管道——东方仙盟筑基期
开发语言·javascript·算法·json·仙盟创梦ide·东方仙盟·东方仙盟算法
EverestVIP1 小时前
c++前置声明的方式与说明
开发语言·c++