编程珠玑第二版习题,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: 首先确定循环不变式,以此作为指导编写主循环并给出返回值


-------------------------------------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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值