赞
踩
二分搜索,也称折半搜索、对数搜索,是一种在有序数组中查找某一特定元素的搜索算法。
二分搜索是一种高效的查找算法,适用于在已排序的数组中查找特定元素。它的基本思想是通过不断将搜索区间对半分割,从而快速缩小查找范围。
二分搜索每次把搜索区域减少一半,时间复杂度为 O(logn)(n代表集合中元素的个数)。
二分搜索的基本步骤如下:
1.初始条件:将搜索范围设为数组的整个区间。
2.查找中间元素:计算当前区间的中间索引。
3.比较中间元素:将中间元素与目标值进行比较:
4.重复步骤 2 和 3,直到找到目标值或搜索范围为空。
在下图中为大家展示了二分搜索的过程:
- #include <iostream>
- #include <vector>
- using namespace std;
-
- int binarySearchRecursive(const vector<int>& arr, int left, int right, int target)
- {
- if (left <= right)
- {
- int mid = left + (right - left) / 2;
- if (arr[mid] == target)
- {
- return mid;
- }
- if (arr[mid] > target)
- {
- return binarySearchRecursive(arr, left, mid - 1, target);
- }
- return binarySearchRecursive(arr, mid + 1, right, target);
- }
- return -1;
- }
-
- int main()
- {
- vector<int> arr = { 2, 3, 4, 10, 40 };
- int target = 10;
- int result = binarySearchRecursive(arr, 0, arr.size() - 1, target);
-
- if (result != -1)
- {
- cout << "元素在索引 " << result << " 处找到" << endl;
- }
- else
- {
- cout << "元素未找到" << endl;
- }
-
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。