编程珠玑第二版习题,4.6.2

把t在数组x中第一次出现的位置返回给p


/**
 * give a index i that arr[i - 1] < x <= arr[i] <= arr[i + 1],
 * say, the smallest index of an array that greater than or equal to x
 * @param arr int array
 * @param x element that we want to search for
 * @param n numbers of the array element
 */
int binary_search(int *arr, int x, int n) {
    int lo = 0;
    int hi = n;

    // invariant: [0, lo) < x <= [hi, n)
    while (lo < hi) {
        int m = (lo + hi) / 2;

        if (arr[m] < x)
            lo = m + 1;
            // since arr[m] < x, in this point, [0, lo) < x
        else
            hi = m;
            // x <= arr[m], and then, x <= arr[hi]
            // that is, x <= [hi, n)

        // invariant: [0, lo) < x <= [hi, n)
    }
    // In line 17, we let lo = m + 1, the range therefore will shrink
    // otherwise, hi = m. 
    //      if m < h, the range is smaller then before
    //      else, if must be m == h, only when lo == hi yield this result, 
    //            the loop will terminate.
    // In a word, the loop will terminate at some point. 
    // At this time, hi must be the index that we wanted
    return hi;
}

note: 首先确定循环不变式,以此作为指导编写主循环并给出返回值

你可能感兴趣的:(search,binary)