I\'m reading \"Introduction to Algorithm\" by CLRS. In chapter 2, the authors mention \"loop invariants\". What is a loop invariant?
Beside all of the good answers, I guess a great example from How to Think About Algorithms, by Jeff Edmonds can illustrate the concept very well:
EXAMPLE 1.2.1 "The Find-Max Two-Finger Algorithm"
1) Specifications: An input instance consists of a list L(1..n) of elements. The output consists of an index i such that L(i) has maximum value. If there are multiple entries with this same value, then any one of them is returned.
2) Basic Steps: You decide on the two-finger method. Your right finger runs down the list.
3) Measure of Progress: The measure of progress is how far along the list your right finger is.
4) The Loop Invariant: The loop invariant states that your left finger points to one of the largest entries encountered so far by your right finger.
5) Main Steps: Each iteration, you move your right finger down one entry in the list. If your right finger is now pointing at an entry that is larger then the left finger’s entry, then move your left finger to be with your right finger.
6) Make Progress: You make progress because your right finger moves one entry.
7) Maintain Loop Invariant: You know that the loop invariant has been maintained as follows. For each step, the new left finger element is Max(old left finger element, new element). By the loop invariant, this is Max(Max(shorter list), new element). Mathe- matically, this is Max(longer list).
8) Establishing the Loop Invariant: You initially establish the loop invariant by point- ing both fingers to the first element.
9) Exit Condition: You are done when your right finger has finished traversing the list.
10) Ending: In the end, we know the problem is solved as follows. By the exit condi- tion, your right finger has encountered all of the entries. By the loop invariant, your left finger points at the maximum of these. Return this entry.
11) Termination and Running Time: The time required is some constant times the length of the list.
12) Special Cases: Check what happens when there are multiple entries with the same value or when n = 0 or n = 1.
13) Coding and Implementation Details: ...
14) Formal Proof: The correctness of the algorithm follows from the above steps.