0% found this document useful (0 votes)
567 views10 pages

Loop Invariants Explained

Loop invariants are statements that must be true before and after each loop iteration. A good loop invariant satisfies initialization by being true before the first iteration, maintenance by remaining true after each iteration if it was true before, and termination by revealing something useful about the algorithm when the loop ends. Examples demonstrate loop invariants for finding the maximum value in an array, binary search, and sorting numbers.

Uploaded by

Muhammad hanzla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
567 views10 pages

Loop Invariants Explained

Loop invariants are statements that must be true before and after each loop iteration. A good loop invariant satisfies initialization by being true before the first iteration, maintenance by remaining true after each iteration if it was true before, and termination by revealing something useful about the algorithm when the loop ends. Examples demonstrate loop invariants for finding the maximum value in an array, binary search, and sorting numbers.

Uploaded by

Muhammad hanzla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

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

You might also like