What "correct" means
An algorithm is correct for a contract (see the previous lesson) if, for every valid input, it stops and its output satisfies the contract. Two separate obligations:
- Partial correctness: if it stops, the answer is right.
- Termination: it does stop.
Testing samples a few inputs out of infinitely many. Edsger Dijkstra put it bluntly: testing can show the presence of bugs, never their absence. For loops, the standard tool for an actual argument is the loop invariant, an idea that goes back to Floyd and Hoare in the 1960s.
Loop invariants
A loop invariant is a statement about the program's variables that is true at the start of every iteration. To use it you check three things:
- Initialization: it is true before the first iteration.
- Maintenance: if it is true at the start of an iteration, it is true at the start of the next.
- Termination: when the loop stops, the invariant plus the stopping condition give you the result you want.
This is induction over the iterations. The art is choosing a statement that is strong enough to give the result at the end, yet simple enough to check.
Insertion sort, proved
Run the lab above with Eight values. Insertion sort takes each element in turn, lifts it out (the key), shifts larger elements of the sorted prefix one slot right, and drops the key into the gap. Pseudocode with the invariants written in:
Pseudocode
for i from 1 to n - 1:
# Outer invariant: slots 0 … i-1 hold the original first i elements, in sorted order.
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
# Inner invariant: every value in slots j+2 … i is > key, and slot j+1 is the gap.
a[j + 1] = a[j]
j = j - 1
a[j + 1] = key
Initialization. Before the first iteration i = 1: slot 0 alone is the original first element,
and a one-element range is sorted.
Maintenance. The inner loop moves each element of the prefix that is greater than the key one
slot right, keeping their relative order, and stops at the first a[j] ≤ key (or at the start).
Everything left of the gap is ≤ key and still sorted; everything right of the gap is > key and
still sorted. Placing the key in the gap therefore makes slots 0 … i sorted, and they contain
exactly the original first i + 1 elements. The lab says the same thing in words at each step:
"Slots 0 to i − 1 are sorted among themselves."
Termination. The outer loop stops with i = n. The invariant now reads: slots 0 … n − 1 hold
the original n elements in sorted order. That is the contract.
Stability for free. The inner loop condition is a[j] > key, a strict comparison, so an equal
element stops the shift and the key lands to its right. Equal values never pass each other: the
Equal values stay in order preset shows the letters keep their original order. Change > to >=
and the algorithm still sorts but is no longer stable. The invariant proof does not notice that
difference, because the contract "sorted" does not mention stability. If you need stability, it
must be in the contract and in the invariant.
Termination: find a quantity that shrinks
To show a loop stops, find a variant: an integer that is never negative while the loop runs and strictly decreases on every iteration. It cannot decrease forever.
| Loop | Variant | Why it decreases |
|---|---|---|
| insertion sort, outer | n - i |
i grows by one per iteration |
| insertion sort, inner | j + 1 |
j drops by one; the loop stops at j = -1 |
| binary search | high - low + 1 |
either it returns, or low or high moves past mid |
| two pointers inward | j - i |
exactly one pointer moves inward |
A variant also gives a bound on the number of iterations, which is where complexity analysis starts: the inner loop of insertion sort runs at most i times, so the total is at most 1 + 2 + … + (n − 1) = n(n − 1)/2 comparisons, the count the Reversed preset reaches (28 for eight values).
Invariants elsewhere in this lab
Many lessons state their invariant explicitly, and it is worth reading them with this lesson in mind:
- Binary search: if the target is present, it lies in
[low, high]. - Two prices that fit the budget: if
a valid pair exists, one exists with both indices in
[left, right]. - Read/write compaction (move zeros):
slots before
writehold exactly the kept elements seen so far, in order. - A running maximum:
bestis the largest value among the elements already visited.
Interval conventions and off-by-one errors
Most off-by-one bugs come from mixing two ways of describing a range:
- inclusive
[low, high]: both ends are candidates; empty whenlow > high; - half-open
[low, high):highis one past the last candidate; empty whenlow == high, and the length is simplyhigh - low.
Pick one convention per loop, write it in the invariant, and check every update against it. The
binary search lesson shows both versions side by side. Half-open ranges are the convention of
Python slices, C++ iterator pairs (begin, end) and most standard library APIs, which is a good
reason to default to them.
Edge cases, systematically
Edge cases are inputs at the boundary of the contract. A list that catches most of them:
| Category | Cases |
|---|---|
| Size | empty, one element, two elements, the maximum allowed size |
| Content | all equal, all distinct, many duplicates |
| Order | already sorted (Already sorted preset), reverse sorted (Reversed), random |
| Position | the answer first, last, in the middle, or absent |
| Values | zero, negative numbers, the smallest and largest representable values |
| Arithmetic | sums or products that overflow, (low + high) / 2 on large indices |
For insertion sort: the empty and one-element arrays skip the outer loop entirely (i starts at 1);
a sorted array makes the inner loop stop immediately every time, so it costs n − 1 comparisons and
no shifts; a reversed array makes every key travel to slot 0, the worst case.
Turning invariants into checks
You can test an invariant while the code runs with an assertion. Each language treats them differently, which matters if you rely on them:
- C#:
Debug.Assert(condition)is marked[Conditional("DEBUG")], so calls are removed from Release builds entirely. Use exceptions for checks that must always run. - Python:
assert condition, messageis removed when Python runs with-O. Never use it to validate user input. - Java:
assert condition : message;is disabled by default and runs only with-ea. This lab's Java tests run with-eafor exactly that reason. - C++:
assert(condition)from<cassert>expands to nothing whenNDEBUGis defined, which release build configurations usually do.
Beyond assertions, this lab checks every algorithm two ways: a shared fixture file of hand-picked cases (including the edge cases above) that all four languages run, and randomized comparisons against a simple reference. For insertion sort the reference is each language's stable built-in sort; the note under the full implementation below says exactly what ran.
Common mistakes
- An invariant that is true but useless, such as "
iis between 1 and n". It must give the result at termination. - Checking only maintenance. Forgetting initialization (the empty prefix) or termination (what the invariant says when the loop exits).
- Mixing inclusive and half-open ranges in one loop.
- Loops whose variant does not always decrease:
low = midwhenmidcan equallowloops forever on a two-element range. - Assertions with side effects (
assert(pop() == x)): the side effect disappears in release builds. - Only testing the happy path and never the empty, single and all-equal inputs.
Worked practice
1. Give a loop invariant for finding the maximum with best = a[0]; for i from 1 to n - 1: best = max(best, a[i]).
At the start of the iteration for index i, best is the maximum of a[0 … i-1]. Initialization:
for i = 1 it is a[0]. Maintenance: max(best, a[i]) is the maximum of a[0 … i]. Termination:
i = n, so best is the maximum of the whole array. The code also reveals an unstated precondition:
a[0] requires n ≥ 1.
2. Why does insertion sort's inner loop test j >= 0 before reading a[j]?
When the key is smaller than everything in the prefix, j reaches -1. Short-circuit evaluation
stops before a[-1] is read. In C#, Java and C++ that read would be out of bounds (an exception, or
undefined behaviour in C++); in Python a[-1] silently reads the last element, a wrong
comparison instead of a crash.
3. What is a variant for while n > 1: n = n // 2, and what does it say about the number of iterations?
n itself: it is positive inside the loop and at least halves each time. Since it halves, the loop
runs ⌊log₂ n⌋ times, which is the halving loop
exercise.
4. List five edge cases for "remove duplicates from a sorted array in place".
Empty array; one element; all elements equal (result length 1); no duplicates (nothing moves); duplicates only at the end (or only at the start). Also negative values and the extremes of the value range, which should behave like any other value.
Summary
- Correct = for every valid input, it stops and the output meets the contract.
- A loop invariant is checked by initialization, maintenance and termination: induction over iterations.
- Termination needs a non-negative integer that strictly decreases; it also bounds the iteration count.
- Insertion sort keeps "the prefix is the original first i elements, sorted"; its strict
>keeps it stable. - Pick one interval convention per loop, test the boundary inputs, and know that assertions vanish in release builds in all four languages.