一、最基本的二分查找,判断一个数在数组中是不是存在的问题

#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;
}

 

相关文章:

  • 2022-12-23
  • 2021-11-09
  • 2021-11-06
  • 2021-10-12
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
猜你喜欢
  • 2020-01-28
  • 2022-12-23
  • 2021-09-12
  • 2022-12-23
  • 2022-12-23
  • 2021-09-19
  • 2021-07-20
相关资源
相似解决方案