Loop Invariants

Example #2: Suppose we want to reverse an array A of size \( n \) by swapping elements from both ends toward the center. Pseudocode:

for (i = 0; i < n/2; i++)
    swap(A[i], A[n-1-i]);;

The loop invariant here is: "At the start of the $i$th iteration, the subarrays A[0..i-1] and A[n-i..n-1] are reversed." This invariant is true because:

  1. Initially, no elements are swapped, and the invariant holds trivially.
  2. In each iteration, the current pair of elements is swapped, extending the reversed section while preserving correctness.
  3. When the loop ends, every pair is swapped exactly once, meaning the entire array is correctly reversed.