AlgoViz

Insertion sort

easy 14 min

Insertion sort builds a sorted prefix one value at a time: it takes the next value, shifts every bigger value in the prefix one slot right, and drops the value into the gap.

Where it shows up

The same pattern appears across everyday software.

  • Python's sorted() and list.sort()

    Timsort finds runs that are already in order and extends short runs to a minimum length (32 to 64) with binary insertion sort before merging them.

  • C++ std::sort and Java's primitive sort

    Introsort in C++ standard libraries and dual-pivot quick sort in Java both hand small partitions (around 16 to 47 elements) to insertion sort, because it has less overhead than recursing further.

  • Sorting a hand of cards

    The everyday version: hold your sorted cards in one hand, pick up a new card and slide it into place from the right.

  • Live leaderboards and sorted feeds

    When scores or events arrive one at a time and the list must stay sorted after every arrival, each new item is inserted into its place, which is insertion sort run online.

  • Re-sorting nearly sorted data

    Game engines re-sort objects by depth every frame and the order barely changes between frames, so insertion sort runs in close to linear time.

  • Embedded and memory-tight code

    Microcontrollers sorting a handful of sensor readings use it because it needs no extra memory, no recursion and only a few lines of code.