二分查找在有序数组中通过不断缩小搜索区间定位目标值,时间复杂度为O(log n)。可采用循环或递归实现:循环方式效率高,避免函数调用开销;递归方式逻辑清晰,便于理解。C++标准库提供std::binary_search、std::lower_bound和std::upper_bound等函数,推荐优先使用以提升开发效率与安全性。手动实现有助于理解原理,但需确保数组有序,否则结果不可预测。

二分查找是一种在有序数组中快速定位目标值的高效算法,时间复杂度为 O(log n)。C++ 中可以通过循环或递归方式手动实现,也可以借助标准库函数完成。
基本原理
二分查找的核心思想是每次将搜索区间缩小一半:
- 设定左边界 left 和右边界 right
- 计算中间位置 mid = left + (right - left) / 2(避免整数溢出)
- 比较 arr[mid] 与目标值:
- 相等:找到目标,返回索引
- 小于目标:搜索右半部分,left = mid + 1
- 大于目标:搜索左半部分,right = mid - 1
- 重复直到区间为空(未找到)
循环实现二分查找
使用 while 循环实现更高效,避免函数调用开销:
int binarySearch(int arr[], int size, int target) {
int left = 0;
int right = size - 1;
<pre class="brush:php;toolbar:false;">while (left <p>}</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2823" title="C++14"><img
src="https://img.php.cn/upload/manual/001/431/639/6ac8b33c327c4749.png" alt="C++14" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="overflowclass">C++14</a>
<p class="overflowclass">C++14 对 C++11 的修正与增强版本,适合旧系统维护和较老工具链兼容。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>递归实现方式
递归写法逻辑清晰,适合理解算法流程:
int binarySearchRecursive(int arr[], int left, int right, int target) {
if (left > right) {
return -1;
}
<pre class="brush:php;toolbar:false;">int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] <p>}</p>使用 C++ 标准库
STL 提供了多个现成的二分查找工具,推荐在实际开发中优先使用:
- std::binary\_search:判断元素是否存在
- std::lower\_bound:返回第一个不小于目标值的迭代器
- std::upper\_bound:返回第一个大于目标值的迭代器
示例代码:
#include <algorithm>
#include <vector><p>std::vector<int> nums = {1, 3, 5, 7, 9};</int></p>
<p>// 检查是否存在
bool found = std::binary_search(nums.begin(), nums.end(), 5);</p>
<p>// 获取位置
auto it = std::lower_bound(nums.begin(), nums.end(), 5);
if (it != nums.end() && *it == 5) {
int index = it - nums.begin();
}</p></vector></algorithm>基本上就这些。手动实现有助于理解原理,标准库则更安全高效。注意前提是数组必须有序,否则结果不可预测。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










