M01 · Algorithmic Thinking

Correctness: Loop Invariants and Edge Cases

Tests can show that code fails; they cannot show that it never fails. A loop invariant is a short statement that is true every time the loop starts an iteration, and it turns "it worked on my examples" into an argument. This lesson proves insertion sort correct step by step, shows how to argue termination, and builds an edge-case checklist.

~30 minBeginnerC# · Python · Java · C++
Curriculum: M01 Algorithmic Thinking · 2 of 2 lessons available

You will be able to

  • State a loop invariant and check its three parts: initialization, maintenance and termination.
  • Prove that insertion sort sorts its input, and say exactly which line keeps it stable.
  • Argue that a loop terminates using a quantity that strictly decreases and cannot go below zero.
  • Choose interval conventions (inclusive or half-open) that make off-by-one errors visible.
  • Build a systematic edge-case list and know how assertions behave in C#, Python, Java and C++.

Helpful before this lesson

    Guidance only. Those modules are planned; the essentials are recapped here.

    Visual walkthrough

    The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

    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:

    1. Initialization: it is true before the first iteration.
    2. Maintenance: if it is true at the start of an iteration, it is true at the start of the next.
    3. 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 write hold exactly the kept elements seen so far, in order.
    • A running maximum: best is 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 when low > high;
    • half-open [low, high): high is one past the last candidate; empty when low == high, and the length is simply high - 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, message is 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 -ea for exactly that reason.
    • C++: assert(condition) from <cassert> expands to nothing when NDEBUG is 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 "i is 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 = mid when mid can equal low loops 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.

    Full implementation

    Insertion sort in four languages, checked against the merge sort fixture (which also verifies stability) and random inputs compared with the language's stable built-in sort.

    namespace Bekadan.Dsa.Examples.Sorting;
     
    /// <summary>
    /// Bubble sort (with the early exit) and insertion sort. Both are stable and in
    /// place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
    /// </summary>
    public static class ElementarySorts
    {
        public static void BubbleSort<T>(T[] items, Comparison<T> compare)
        {
            for (int end = items.Length - 1; end > 0; end--)
            {
                bool swapped = false;
                for (int i = 0; i < end; i++)
                {
                    if (compare(items[i + 1], items[i]) < 0) // strictly smaller: equal items never swap (stable)
                    {
                        (items[i], items[i + 1]) = (items[i + 1], items[i]);
                        swapped = true;
                    }
                }
                if (!swapped)
                    break; // no swap in a whole pass: already sorted
            }
        }
     
        public static void InsertionSort<T>(T[] items, Comparison<T> compare)
        {
            for (int i = 1; i < items.Length; i++)
            {
                T key = items[i];
                int j = i - 1;
                while (j >= 0 && compare(items[j], key) > 0) // strictly greater: equal items stay in order (stable)
                {
                    items[j + 1] = items[j];
                    j--;
                }
                items[j + 1] = key;
            }
        }
    }
    

    Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Sorting/ElementarySorts.cs

    """Bubble sort (with the early exit) and insertion sort.
     
    Both are stable and in place: Θ(n²) comparisons in the worst case, Θ(n) on
    already sorted input.
    """
     
    from collections.abc import Callable
    from typing import Any
     
     
    def _identity(item: Any) -> Any:
        return item
     
     
    def bubble_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
        for end in range(len(items) - 1, 0, -1):
            swapped = False
            for i in range(end):
                if key(items[i + 1]) < key(items[i]):  # strictly smaller: equal items never swap (stable)
                    items[i], items[i + 1] = items[i + 1], items[i]
                    swapped = True
            if not swapped:
                break  # no swap in a whole pass: already sorted
     
     
    def insertion_sort(items: list[Any], key: Callable[[Any], Any] = _identity) -> None:
        for i in range(1, len(items)):
            current = items[i]
            j = i - 1
            while j >= 0 and key(items[j]) > key(current):  # strictly greater: equal items stay in order (stable)
                items[j + 1] = items[j]
                j -= 1
            items[j + 1] = current
    

    Tested on CPython 3.14.0 · examples/python/dsa_examples/elementary_sorts.py

    package dev.bekadan.dsa.sorting;
     
    import java.util.Comparator;
     
    /**
     * Bubble sort (with the early exit) and insertion sort. Both are stable and in
     * place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
     */
    public final class ElementarySorts {
        private ElementarySorts() {
        }
     
        public static <T> void bubbleSort(T[] items, Comparator<? super T> comparator) {
            for (int end = items.length - 1; end > 0; end--) {
                boolean swapped = false;
                for (int i = 0; i < end; i++) {
                    if (comparator.compare(items[i + 1], items[i]) < 0) { // strictly smaller: equal items never swap (stable)
                        T tmp = items[i];
                        items[i] = items[i + 1];
                        items[i + 1] = tmp;
                        swapped = true;
                    }
                }
                if (!swapped) {
                    break; // no swap in a whole pass: already sorted
                }
            }
        }
     
        public static <T> void insertionSort(T[] items, Comparator<? super T> comparator) {
            for (int i = 1; i < items.length; i++) {
                T key = items[i];
                int j = i - 1;
                while (j >= 0 && comparator.compare(items[j], key) > 0) { // strictly greater: equal items stay in order
                    items[j + 1] = items[j];
                    j--;
                }
                items[j + 1] = key;
            }
        }
    }
    

    Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/sorting/ElementarySorts.java

    #pragma once
     
    #include <cstddef>
    #include <functional>
    #include <span>
    #include <utility>
     
    namespace bekadan::dsa {
     
    // Bubble sort (with the early exit) and insertion sort. Both are stable and in
    // place: Θ(n²) comparisons in the worst case, Θ(n) on already sorted input.
     
    template <typename T, typename Less = std::less<>>
    void bubble_sort(std::span<T> items, Less less = {}) {
        for (std::size_t end = items.size(); end > 1; --end) {
            bool swapped = false;
            for (std::size_t i = 0; i + 1 < end; ++i) {
                if (less(items[i + 1], items[i])) {  // strictly smaller: equal items never swap (stable)
                    std::swap(items[i], items[i + 1]);
                    swapped = true;
                }
            }
            if (!swapped)
                break;  // no swap in a whole pass: already sorted
        }
    }
     
    template <typename T, typename Less = std::less<>>
    void insertion_sort(std::span<T> items, Less less = {}) {
        for (std::size_t i = 1; i < items.size(); ++i) {
            T key = std::move(items[i]);
            std::size_t j = i;  // the gap is at j; compare with items[j - 1]
            while (j > 0 && less(key, items[j - 1])) {  // strictly greater on the left: equal items stay in order
                items[j] = std::move(items[j - 1]);
                --j;
            }
            items[j] = std::move(key);
        }
    }
     
    }  // namespace bekadan::dsa
    

    Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/elementary_sorts.hpp

    References