二分查找的两种写法

时间:2021-03-12 18:33:12
bool Bin_Search(const int *pre, int low, int high, const int key)
{
    while(low < high)    //注意
    {
        int mid = low + ((high-low)>>1);
        if(pre[mid] == key) return true;
        else if(pre[mid] < key) low = mid + 1;
        else high = mid;    //注意
    }
    return false;
}

bool Bin_Search(const int *pre, int low, int high, const int key)
{
    high--;
    while(low <= high)
    {
        int mid = low + ((high-low)>>1);
        if(pre[mid] == key) return true;
        else if(pre[mid] < key) low = mid + 1;
        else high = mid + 1;
    }
    return false;
}