I'm reading "Introduction to Algorithm" by CLRS. In chapter 2, the authors mention "loop invariants". What is a loop invariant?
相关问题
- Finding k smallest elements in a min heap - worst-
- binary search tree path list
- High cost encryption but less cost decryption
- How to get a fixed number of evenly spaced points
- Space complexity of validation of a binary search
相关文章
- What are the problems associated to Best First Sea
- Coin change DP solution to keep track of coins
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Algorithm for maximizing coverage of rectangular a
- How to measure complexity of a string?
- Select unique/deduplication in SSE/AVX
- How to smooth the blocks of a 3D voxel world?
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.
Loop invariant is a mathematical formula such as
(x=y+1)
. In that example,x
andy
represent two variables in a loop. Considering the changing behavior of those variables throughout the execution of the code, it is almost impossible to test all possible tox
andy
values and see if they produce any bug. Lets sayx
is an integer. Integer can hold 32 bit space in the memory. If that number exceeds, buffer overflow occurs. So we need to be sure that throughout the execution of the code, it never exceeds that space. for that, we need to understand a general formula that shows the relationship between variables. After all, we just try to understand the behavior of the program.In simple words, a loop invariant is some predicate (condition) that holds for every iteration of the loop. For example, let's look at a simple
for
loop that looks like this:In this example it is true (for every iteration) that
i + j == 9
. A weaker invariant that is also true is thati >= 0 && i <= 10
.