二分查找算法

#include <iostream>
#include <vector>
using namespace std;

int binarySearch(vector<int>&vec, int target)
{

    int left = 0;
    int right = vec.size() - 1;
    int mid = (left + right)/2;

    while(left < right)
    {
        if (vec[mid] == target) //注意
        {
            return mid;
        }
        else if (vec[mid] > target)
        {
            right = mid-1;
        }
        else if (vec[mid] < target)
        {
            left = mid + 1;
        }
        mid = (left + right)/2; // 注意
    }
    return -1;
}

int main()
{
    int target = 5;
    vector<int> vec;
    for(int i = 0; i< 10; i++)
        vec.push_back(i);
    cout << binarySearch(vec, target);

    return 0;
}

 

posted @ 2020-03-06 16:51  Lucky&  阅读(164)  评论(0编辑  收藏  举报
//返回顶部开始
//返回顶部结束