Insertion sort 2026-10-13
Insertion sort grows a sorted prefix of an array one entry at a time. In the adjacent-swap version, start with position , compare its current sort key with the preceding sort key, and swap the complete sorting records only when the right sort key is strictly smaller. Continue leftward until no swap is needed or the entry reaches position zero; then process original position . A tie stops the pass. This is the strict comparison and exchange rule in the authored implementation.[ref]
Take , where the subscript labels a complete sorting record and comparisons inspect only its sort key. Starting from index zero, the complete key-comparison trace is:
The loop invariant is that, before pass , positions satisfy sortedness and contain precisely the entries originally in that prefix. Moving the next entry left through strictly larger sort keys extends that prefix, and every swap retains sorting permutation preservation. Equal-key entries never cross, giving stable sorting. Each leftward step decreases the position, and each completed pass increases the prefix length, so the algorithm terminates.
With constant-cost key comparisons and swaps, reverse-ordered distinct sort keys cause comparisons and swaps. Thus worst-case time complexity is in Big O notation. An already sorted array needs only key comparisons for and no swaps. The adjacent-swap version uses constant auxiliary space complexity. Small or nearly sorted arrays can therefore make insertion sort useful despite its quadratic worst case.
Robert Sedgewick (computer scientist) Created 2026-10-24 Updated 2026-11-05
Robert Sedgewick coauthored Algorithms, 4th edition by Robert Sedgewick and others and Introduction to Programming in Java: An Interdisciplinary Approach by Robert Sedgewick and others. The books connect algorithms and data structures with implementations and cost analysis. For example, Insertion.java by Robert Sedgewick and others exposes how insertion sort shifts data and compares keys, making its behaviour available for direct inspection.[ref]
Insertion.java by Robert Sedgewick and others. implementation and class documentation
Portrait of Robert Sedgewick (computer scientist)
. Animalspirits; existing crop by Filetime. Creative Commons Attribution-ShareAlike 4.0 International, via Wikimedia Commons. Source.
