What is a loop invariant?

后端 未结 15 1346
后悔当初
后悔当初 2020-11-28 17:13

I\'m reading \"Introduction to Algorithm\" by CLRS. In chapter 2, the authors mention \"loop invariants\". What is a loop invariant?

15条回答
  •  北海茫月
    2020-11-28 17:38

    The Loop Invariant Property is a condition that holds for every step of a loops execution (ie. for loops, while loops, etc.)

    This is essential to a Loop Invariant Proof, where one is able to show that an algorithm executes correctly if at every step of its execution this loop invariant property holds.

    For an algorithm to be correct, the Loop Invariant must hold at:

    Initialization (the beginning)

    Maintenance (each step after)

    Termination (when it's finished)

    This is used to evaluate a bunch of things, but the best example is greedy algorithms for weighted graph traversal. For a greedy algorithm to yield an optimal solution (a path across the graph), it must reach connect all nodes in the lowest weight path possible.

    Thus, the loop invariant property is that the path taken has the least weight. At the beginning we haven't added any edges, so this property is true (it isn't false, in this case). At each step, we follow the lowest weight edge (the greedy step), so again we're taking the lowest weight path. At the end, we have found the lowest weighted path, so our property is also true.

    If an algorithm doesn't do this, we can prove that it isn't optimal.

提交回复
热议问题