二分查找在有序数组中以O(log n)时间复杂度快速定位目标值,通过维护left和right指针,计算mid = left + (right - left) / 2避免溢出,比较arr[mid]与target决定搜索区间,迭代或递归实现,C++ STL提供binary_search、lower_bound、upper_bound等函数简化操作,使用时需确保数组有序并正确处理边界条件。

二分查找是一种在有序数组中快速查找目标值的高效算法,时间复杂度为 O(log n)。它通过不断缩小搜索范围,将问题规模每次减半,从而实现快速定位。C++ 中可以使用标准库函数,也可以手动实现。下面详细介绍其原理和代码实现。
二分查找的前提是数组必须有序(升序或降序)。算法核心思想如下:
1. 迭代版本(推荐,效率高)
#include <iostream>
#include <vector>
using namespace std;
<p>int binarySearch(vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;</p><pre class='brush:php;toolbar:false;'>while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // 未找到}
立即学习“C++免费学习笔记(深入)”;
// 示例调用
int main() {
vector
2. 递归版本
int binarySearchRecursive(vector<int>& arr, int target, int left, int right) {
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] < target)
return binarySearchRecursive(arr, target, mid + 1, right);
else
return binarySearchRecursive(arr, target, left, mid - 1);}
立即学习“C++免费学习笔记(深入)”;
// 调用方式:binarySearchRecursive(nums, 7, 0, nums.size()-1);
C++ STL 提供了多个用于二分查找的函数,定义在
示例:
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
<p>int main() {
vector<int> nums = {1, 3, 5, 7, 7, 7, 9, 11};</p><pre class='brush:php;toolbar:false;'>// 判断是否存在
bool found = binary_search(nums.begin(), nums.end(), 7);
// 查找第一个 >=7 的位置
auto it1 = lower_bound(nums.begin(), nums.end(), 7);
cout << "lower_bound at: " << (it1 - nums.begin()) << endl;
// 查找第一个 >7 的位置
auto it2 = upper_bound(nums.begin(), nums.end(), 7);
cout << "upper_bound at: " << (it2 - nums.begin()) << endl;
return 0;}
立即学习“C++免费学习笔记(深入)”;
使用 STL 函数能减少出错概率,尤其在处理边界情况时更安全。
基本上就这些。掌握二分查找对刷题和实际开发都很有帮助,理解逻辑比死记代码更重要。
以上就是c++++ 二分查找代码 c++二分查找算法详解的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号