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

相关推荐
田里的水稻1 小时前
FA_规划和控制(PC)-瑞德斯.谢普路径规划(RSPP))
人工智能·算法·数学建模·机器人·自动驾驶
罗湖老棍子1 小时前
【例 1】二叉苹果树(信息学奥赛一本通- P1575)
算法·树上背包·树型动态规划
元亓亓亓2 小时前
LeetCode热题100--76. 最小覆盖子串--困难
算法·leetcode·职场和发展
CHANG_THE_WORLD2 小时前
C++数组地址传递与数据影响:深入理解指针与内存
算法
json{shen:"jing"}2 小时前
力扣-单词拆分
数据结构·算法
星火开发设计2 小时前
序列式容器:deque 双端队列的适用场景
java·开发语言·jvm·c++·知识
aaa7872 小时前
Codeforces Round 1080 (Div. 3) 题解
数据结构·算法
草履虫建模2 小时前
Java 集合框架:接口体系、常用实现、底层结构与选型(含线程安全)
java·数据结构·windows·安全·决策树·kafka·哈希算法
LYS_06182 小时前
c++学习(1)(编译过程)
c++·学习
特种加菲猫2 小时前
C++核心语法入门:从命名空间到nullptr的全面解析
开发语言·c++