循环不变式
循环不变式就是在进行循环时,在每次循环都保持不变的逻辑表达式,相当于数学归纳法证明的“断言”。
算法导论第二章中关于循环不变式原文如下:
We state these properties of A[1 ‥ j -1] formally as a loop invariant。
We use loop invariants to help us understand why an algorithm is correct. We must show three things about a loop invariant:
- Initialization: It is true prior to the first iteration of the loop.
- Maintenance: If it is true before an iteration of the loop, it remains true before the next iteration.
- Termination: When the loop terminates, the invariant gives us a useful property that helps show that the algorithm is correct.
这里举了插入排序的例子,每次循环从数组A中取出第j个元素插入有序区A[1 .. j-1],然后递增j。这样A[1 .. j-1]的有序性始终得到保持,这就是所谓的“循环不变”。
1. 初始化(循环第一次迭代之前)的时候,A[1 ‥ j -1]的“有序性”是成立的;
2. 在循环的每次迭代过程中,A[1 ‥ j -1]的“有序性”仍然保持;
3. 循环结束的时候,A[1 ‥ j -1]的“有序性”仍然成立。
循环不变性的定义跟数学归纳法的证明过程有些相似,在第一次循环的时候,取出第1个元素,排入有序区A[1],A是有序的,在每次循环中,都将插入一个元素到有序数组A中,同时保持A的有序,循环结束时,A中的有序依然成立,可以得出下述断言M(n),这个断言就是循环不变式:
M(n):每次循环从数组A中取出第j个元素插入有序区A[1 .. j-1],然后递增j,这样A[1 .. j-1]的有序性始终得到保持。
而其中的递增j,是为了让循环适时结束。
可以参考《程序员的数学》第四章内容。