二进制搜索(Binary Search)是一种高效的查找算法,适用于已排序的数据集。它通过反复将查找范围减半来快速定位目标值。二进制搜索的时间复杂度为O(log n),比线性搜索(O(n))更高效。
向量(Vector)是C++标准库中的一个动态数组容器,能够自动管理内存,并提供高效的随机访问能力。
类型:
应用场景:
以下是一个使用C++向量实现二进制搜索的示例:
#include <iostream>
#include <vector>
// 标准二进制搜索函数
int binarySearch(const std::vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
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; // 未找到目标值
}
// 查找插入位置的函数
int searchInsertPosition(const std::vector<int>& arr, int target) {
int left = 0;
int right = arr.size() - 1;
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 left; // 返回插入位置
}
int main() {
std::vector<int> vec = {1, 3, 5, 6};
int target = 5;
int index = binarySearch(vec, target);
std::cout << "Binary Search Result: " << index << std::endl;
int insertPos = searchInsertPosition(vec, 2);
std::cout << "Insert Position for 2: " << insertPos << std::endl;
return 0;
}
问题1:未找到目标值但未返回-1
left <= right
且每次循环后正确更新left
和right
。问题2:数组越界
int mid = left + (right - left) / 2;
而非(left + right) / 2
。问题3:性能低下
通过上述方法,可以有效避免和解决在使用向量进行二进制搜索时可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云