二分搜索(C++泛型)

使用C++模板语法,遵循C++11标准

template <typename T, typename It>
It binary_search(It beg, It end, const T &val)
{
    auto mid = beg + (end - beg) / 2;
    while (mid != end && *mid != val)
    {
        if (val < *mid)
        {
            end = mid;
        }
        else
        {
            beg = mid + 1;
        }
        mid = beg + (end - beg) / 2;
    }
    return mid;
}

测试:

int main()
{
    vector<int> v{1, 2, 3, 4, 5, 6, 7};
    auto a = binary_search(v.begin(), v.end(), 7);
    if (a != v.end())
    {
        cout << *a << endl;
    }
    return 0;
}