对算法导论中用循环不变式证明算法正确性的理解

来源:互联网 发布:布鲁斯威利斯 知乎 编辑:程序博客网 时间:2024/05/19 00:38

算法导论中原文:

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.


When the first two properties hold, the loop invariant is true prior to every iteration
of the loop. (Of course, we are free to use established facts other than the loop
invariant itself to prove that the loop invariant remains true before each iteration.)
Note the similarity to mathematical induction, where to prove that a property holds,
you prove a base case and an inductive step. Here, showing that the invariant holds
before the first iteration corresponds to the base case, and showing that the invariant
holds from iteration to iteration corresponds to the inductive step.
The third property is perhaps the most important one, since we are using the loop
invariant to show correctness. Typically, we use the loop invariant along with the
condition that caused the loop to terminate. The termination property differs from
how we usually use mathematical induction, in which we apply the inductive step
infinitely; here, we stop the “induction” when the loop terminates.


首先回顾一下数学归纳法:

最简单和常见的数学归纳法是证明当n等于任意一个自然数时某命题成立。证明分下面两步:

  1. 证明当n = 1时命题成立。
  2. 证明如果在n = m时命题成立,那么可以推导出在n = m+1时命题也成立。(m代表任意自然数)

这种方法的原理在于:首先证明在某个起点值时命题成立,然后证明从一个值到下一个值的过程有效。当这两点都已经证明,那么任意值都可以通过反复使用这个方法推导出来。把这个方法想成多米诺效应也许更容易理解一些。例如:你有一列很长的直立着的多米诺骨牌,如果你可以:

  1. 证明第一张骨牌会倒。
  2. 证明只要任意一张骨牌倒了,那么与其相邻的下一张骨牌也会倒。

那么便可以下结论:所有的骨牌都会倒。



个人理解,循环不变式(性)从本质上应该类似于数学归纳法中要证明的那个公式或者性质相当于上面提到的n=m成立这一性质,首先证明循环不变式成立(性)(Initialization)(Maintenance),即循环1到无穷次某个性质都成立。对于算法来说总会终止,当算法结束时,即当n等于某个特定值时,性质依然是成立的,该结果就是算法要得到的结果,当然该结果也是正确的。

对于Insertion-sort算法来说,循环不变式(性)就是“A[1...j-1]已经排好序,而且排好序的数组A中的数据都是原来A[1...j-1]中的数据”。因此,只要通过Initialization)(Maintenance)证明循环不变式(性)是成立的,而且当算法终止即迭代到j=A.length+1时同样是满足循环不变式(性)的,即A[1...A.length]已经排好序,同时也说明算法的结果是正确的。



参考:

http://zh.wikipedia.org/wiki/%E6%95%B0%E5%AD%A6%E5%BD%92%E7%BA%B3%E6%B3%95


原创粉丝点击