一、最基本的二分查找,判断一个数在数组中是不是存在的问题
#include<iostream> #include<vector> using namespace std; int binary_search(vector<int>& arr, int left, int right, int target) { 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 main() { vector<int> arr = { 1, 3, 5, 7, 11, 8 }; int target = 5; int left = 0; int right = arr.size() - 1; int result = -1; result = binary_search(arr, left, right, target); cout << "结果是:" << result << endl; return 0; }