看来就是在循环内及循环结束的时候都成立的表达式
一般而言,用这个式子表示希望得到的结果,如果在循环的每一步,这个式子都是正确的,那么循环结束后,这个式子也正确,并得到了期望的结果.
例子是这样的:
QUOTE:
apvector<int> list(n); // n is some positive integer
int k, indexMax;
<code which assigns values to all entries in list>
indexMax = 0;
for(k = 1; k < list.length(); k++){
// invariant true here
if (list[k] > list[indexMax])
indexMax = k;
}
这是一个很简单的求最大值(在数组中的下标)的问题,在循环内// invariant true here 处可以指明始终成立的不变式为:
算法导论第二章中的原文是:We state these properties of A[1 ‥ j -1] formally as a loop invariant。其中举的例子是插入排序,每次循环从数组A中取出第j个元素插入有序区A[1 .. j-1],然后递增j。这样A[1 .. j-1]的有序性始终得到保持,这就是所谓的“循环不变”了。
这个概念主要用来检验算法的正确性。
原文如下: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.