2013年9月28日 星期六

[EPI] Binary Search

int binary_search(int key, const std::vector<int>& sequence)
{
    int L = 0;
    int U = sequence.size() - 1;

    while (L <= U)
    {
        int M = L + (U - L)/2; // avoid overflow while writing M = (L + U)/2
        if (sequence[M] < key)
        {
            L = M + 1;
        }
        else if (sequence[M] > key)
        {
            U = M - 1;
        }
        else
        {
            return M;
        }
    }
    return -1;
}


一直沒有規規矩矩的學懂 binary search implementation in C++

1 則留言: