循环不变式与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