二分查找在有序数组中以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#include using namespace std; int binarySearch(vector
& arr, int target) { int left = 0 ; int right = arr.size() - 1;
while (left zuojiankuohaophpcn= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] zuojiankuohaophpcn target) { left = mid + 1; } else { right = mid - 1; } } return -1; // 未找到}
// 示例调用 int main() { vector
nums = {1, 3, 5, 7, 9, 11, 13}; int index = binarySearch(nums, 7); if (index != -1) cout
2. 递归版本
int binarySearchRecursive(vector& arr, int target, int left, int right) { if (left > right) return -1; int mid = left + (right - left) / 2; if (arr[mid] == target) return mid; else if (arr[mid] zuojiankuohaophpcn target) return binarySearchRecursive(arr, target, mid + 1, right); else return binarySearchRecursive(arr, target, left, mid - 1);}
// 调用方式:binarySearchRecursive(nums, 7, 0, nums.size()-1);
C++ STL 提供了多个用于二分查找的函数,定义在 gorithm> 头文件中:
示例:
#include #include#include using namespace std; int main() { vector
nums = {1, 3, 5, 7, 7, 7, 9, 11}; // 判断是否存在 bool found = binary_search(nums.begin(), nums.end(), 7); // 查找第一个 >=7 的位置 auto it1 = lower_bound(nums.begin(), nums.end(), 7); cout zuojiankuohaophpcnzuojiankuohaophpcn "lower_bound at: " zuojiankuohaophpcnzuojiankuohaophpcn (it1 - nums.begin()) zuojiankuohaophpcnzuojiankuohaophpcn endl; // 查找第一个 >7 的位置 auto it2 = upper_bound(nums.begin(), nums.end(), 7); cout zuojiankuohaophpcnzuojiankuohaophpcn "upper_bound at: " zuojiankuohaophpcnzuojiankuohaophpcn (it2 - nums.begin()) zuojiankuohaophpcnzuojiankuohaophpcn endl; return 0;}
使用 STL 函数能减少出错概率,尤其在处理边界情况时更安全。
基本上就这些。掌握二分查找对刷题和实际开发都很有帮助,理解逻辑比死记代码更重要。