Loop Invariants
Loop invariant definition
• A loop invariant is a statement/property of a program loop that is true before
and after each iteration of a loop.
• A good loop invariant should satisfy three properties:
• Initialization: The loop invariant must be true before the first execution of
the loop.
• Maintenance: If the invariant is true before an iteration of the loop, it
should be true also after the iteration.
• Termination: When the loop is terminated the invariant should tell us
something useful, something that helps us understand the algorithm.
• Loop invariant is used to prove correctness of an algorithm.
Initialization: j=2
Maintenance: j=k
Termination: j=length(A)+1
Version 2: Find max
Initialization: j=length(A)
Maintenance: j=k
Termination: j=0
Binary Search
Binary Search
Binary Search
Sorting Numbers