对算法导论中用循环不变式证明算法正确性的理解
来源:互联网 发布:布鲁斯威利斯 知乎 编辑:程序博客网 时间: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等于任意一个自然数时某命题成立。证明分下面两步:
- 证明当n = 1时命题成立。
- 证明如果在n = m时命题成立,那么可以推导出在n = m+1时命题也成立。(m代表任意自然数)
这种方法的原理在于:首先证明在某个起点值时命题成立,然后证明从一个值到下一个值的过程有效。当这两点都已经证明,那么任意值都可以通过反复使用这个方法推导出来。把这个方法想成多米诺效应也许更容易理解一些。例如:你有一列很长的直立着的多米诺骨牌,如果你可以:
- 证明第一张骨牌会倒。
- 证明只要任意一张骨牌倒了,那么与其相邻的下一张骨牌也会倒。
那么便可以下结论:所有的骨牌都会倒。
个人理解,循环不变式(性)从本质上应该类似于数学归纳法中要证明的那个公式或者性质,相当于上面提到的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
- 对算法导论中用循环不变式证明算法正确性的理解
- 算法学习二:循环不变式证明算法的正确性
- 用归纳法证明循环不变式的正确性。
- 用循环不变式证明RB-INSERT-FIXUP的正确性
- 用循环不变式证明RB-DELETE-FIXUP的正确性
- 算法导论学习-数学归纳法与循环不变式理解
- krusal算法正确性的证明
- 用循环不变式证明BINOMIAL-HEAP-UNION(H1, H2)的正确性
- 算法正确性证明三要素
- 贪心算法正确性证明
- 全排列算法的正确性证明
- 哈夫曼树构造算法的正确性证明
- 算法导论 第二章 循环不变式(loop invariant)
- 算法导论-循环不变式、插入排序、归并排序
- 「算法导论」:到底什么是循环不变式?
- 如何理解算法的正确性
- 证明求解约瑟夫斯问题的二进制左循环算法的正确性
- 循环不变性(loop invariant)-证明算法的正确性的一种方法
- shared_ptr解析
- 你真的理解Java的this和super吗?
- 忠实的朋友
- Flex组件出错(一)
- 问题解决:Ubuntu 12.04 Gedit 中文乱码问题
- 对算法导论中用循环不变式证明算法正确性的理解
- 配置struts开发环境,写第一个struts程序
- 关于GCC的理解——On the understanding of the GCC
- 基于virtio在虚拟机与主机之间传递消息
- 学习笔记之有关杀毒软件对软件运行的影响
- 初探js特效魅力之无缝滚动
- oracle sql 执行计划分析(一)
- 类的开始
- HDU 4614(线段树)