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

相关推荐
lvxiangyu115 小时前
MPPI 算法证明重构:基于无穷维泛函变分与 KL 散度的构造性推导
算法·重构·最优控制·随机最优控制
2301_818419016 小时前
C++中的解释器模式变体
开发语言·c++·算法
爱学习的大牛1236 小时前
windows tcpview 类似功能 c++
c++
ab1515176 小时前
3.25完成*23、*24、*28、*30、*33、*38、*39、*40
算法
颜酱6 小时前
回溯算法实战练习(3)
javascript·后端·算法
biter down6 小时前
C++11 统一列表初始化+std::initializer_list
开发语言·c++
ShineWinsu7 小时前
爬虫对抗:ZLibrary反爬机制实战分析技术文章大纲
c++
小王不爱笑1327 小时前
G1 GC 的核心基础:Region 模型的补充细节
java·jvm·算法
小王不爱笑1328 小时前
三色标记算法
算法
charlie1145141918 小时前
通用GUI编程技术——Win32 原生编程实战(十六)——Visual Studio 资源编辑器使用指南
开发语言·c++·ide·学习·gui·visual studio·win32