二分查找函数
Shixuanming12345 · · 个人记录
在C++中,二分查找(也称为二分搜索)是一种在有序数组中查找特定元素的高效算法。二分查找通过将待查找的区间分成两半,判断待查找元素可能存在的区间,从而不断缩小查找范围,直至找到元素或确定元素不存在。下面是如何在C++中实现二分查找函数的示例代码:
- 递归实现
#include <iostream> #include <vector> int binarySearchRecursive(const std::vector<int>& arr, int left, int right, int x) { if (right >= left) { int mid = left + (right - left) / 2; if (arr[mid] == x) return mid; if (arr[mid] > x) return binarySearchRecursive(arr, left, mid - 1, x); return binarySearchRecursive(arr, mid + 1, right, x); } return -1; } int main() { vector<int> arr = {2, 3, 4, 10, 40}; int n = arr.size(); int x = 10; // 要查找的元素 int result = binarySearchRecursive(arr, 0, n - 1, x); if (result == -1) { cout << "Element is not present in array"; } else { cout << "Element is present at index " << result; } return 0; }