Worked Examples: Correctness of Algorithms

These examples are designed to step through the logical process of applying the algorithmic concepts.

Example 1: Sum Array
❓ Problem: Invariant for code summing array A.
💡 Solution: At start of loop i, 'sum' equals sum of A[0..i-1].
Example 2: Max Finding
❓ Problem: Invariant for Finding Max.
💡 Solution: 'max' holds largest value in A[0..i-1].
Example 3: Selection Sort
❓ Problem: State Invariant.
💡 Solution: Subarray A[0..i-1] contains the i smallest elements in sorted order.
Example 4: Binary Search
❓ Problem: State Invariant.
💡 Solution: If target exists, it is in A[low..high].
Example 5: Termination
❓ Problem: Why does Binary Search terminate?
💡 Solution: Range size (high-low) decreases strictly monotonically.
Example 6: Bubble Sort
❓ Problem: State Invariant (Outer loop).
💡 Solution: Subarray A[n-i..n] contains the i largest elements in sorted order.