把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: 首先确定循环不变式,以此作为指导编写主循环并给出返回值
-------------------------------------11/20/2016------------------------------------
并不能保证每次循环,区间都有缩小
正确解法
int binsearch(int x, int v[], int n) {
int lo = 0;
int hi = n - 1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (v[mid] < x) lo = mid + 1;
else hi = mid - 1;
}
return lo;
}
invariant:
[0, lo) < x
(hi, n) >= x