循环不变式与lower_bound证明

循环不变式与lower_bound证明


作用

用于证明循环算法的正确性,跟数学归纳法类似,区别在于数学归纳法可以无限循环下去,循环不变式必须有终止条件.


过程

  • 建立循环不变式.
  • 初始化:循环开始之前的初始条件下,循环不变式成立.
  • 保持:循环的某次迭代之前循环不变式成立,下次迭代之前它仍成立.
  • 终止:终止条件下,循环不变式能够产生结果.

Examples

LowerBound

说明
借鉴std::lower_bound的方法,使用二分法查找在数组A中查找第一个不小于target的索引.
e.g. A[7]={1,2,2,4,4,5,8}, target = 4.
LowerBound(A,0,7,4) = 4
LowerBound(A,0,7,3) = 4
LowerBound(A,0,7,9) = 7
LowerBound(A,0,7,0) = 0

函数定义

    int LowerBound(int A[], int l, int r, int target){
        int i, count, step;
        count = r - l + 1;
        while(count != 0){
            i = l;
            step = count / 2;
            i += step;
            if(target > A[i]){
                i += 1;
                l = i;
                count -= step+1;
            }else{
                count = step;
            }
        }
        return l;
    }

循环不变式证明

//定义循环不变式locatedin(l,count),表示第一个不小于target的索引位于以l为起点,长度为count+1的数组中.对应的notin(l,count)表示不在
    int LowerBound(int A[], int l, int r, int target){
        int i, count, step;
        count = r - l + 1;
        //初始化
        //{locatedin(l, count)}
        //保持
        while(count != 0){
            //{locatedin(l,count)}
            i = l;
            //{locatedin(l,count) && i == l}
            step = count / 2;
            i += step;
            //{locatedin(l,count) && i == l + count/2}
            if(target > A[i]){
                //{locatedin(l,count) && A[l]<=A[l+1]...<=A[i]<target}
                //{locatedin(i+1,count-step-1) && notin(l,step)}
                i += 1;
                //{locatedin(i,count-step-1)}
                count -= step+1;
                //{locatedin(i,count)}
                l = i;
                //{locatedin(l,count)}  loop invariant      
            }else{
                //{locatedin(l,count) && target<=A[i]<=A[i+1]...<=A[r]}
                //{locatedin(l,step)}
                count = step;
                //{locatedin(l,count)}  loop invariant
            }
        }
        //终止条件:count==0
        //{locate(l,0)}说明不小于target的索引位于以l为起点,长度为1的子数组中,也就是A[l],所以最终结果为l
        return l;
    }

[1]: http://blog.csdn.net/richardzrc/article/details/25200205
[2]: http://en.wikipedia.org/wiki/Loop_invariant
[3]: http://www.cs.uofs.edu/~mccloske/courses/cmps144/invariants_lec.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值