首页 > 代码库 > 二分查找

二分查找

template<typename comparable>int binarySearch(const vector<comparable> &a, const comparable &x){    int low = 0, high = a.size() - 1;    while(low <= high)    {        int center = (high + low)/2;        if(x < a[center])            high = center - 1;        else if(x > a[center])            low = center + 1;        else            return center;    }    return -1;}