二分查找

不对称边界(指针形式):

int* binary_search(int *t, int n, int x){
    int *lo = t;
    int *hi = t + n;
    while(lo < hi){ // <
        //int *mid = lo + (hi - lo) / 2; 
        int *mid = lo + (hi - lo) >> 1;
        if(x < *mid){
            hi = mid;
        }else if(x > *mid){
            lo = mid + 1;
        }else{
            return mid;
        }
    }
    return NULL;
}

对称边界(数组):

int *binary_search(int *t, int n, int x){
    int lo = 0;
    int hi = n - 1;

    while(lo <= hi){  // <=
        int mid = lo + (hi - lo) >> 1;
        if(x < t[mid]){
            hi = mid - 1;
        }else if(x > t[mid]){
            lo = mid + 1;
        }else{
            return t + mid;
        }
    }
    return NULL;
}
点赞