"Everyone learns bubble sort and then learns to sneer at it. But one of these 'slow' O(n²) sorts is quietly inside the fast sorts you actually use — because on small or nearly-sorted data, simple beats clever."
The Three Teaching Sorts
All three are O(n²) — they compare pairs in nested loops — but each illustrates a different idea:
- Bubble sort: repeatedly swap adjacent out-of-order pairs; the largest 'bubbles' to the end each pass. The simplest to picture, almost never the right choice in practice — its main job is being the first sort everyone meets.
- Selection sort: selects the minimum for each remaining position. It uses at most O(n) swaps and often writes less than bubble sort, but it does not universally minimize swaps among all sorting algorithms. Comparisons remain O(n²).
- Insertion sort: builds a sorted prefix one element at a time, inserting each new element into its place — exactly how most people sort a hand of cards.
Why Insertion Sort Earns Its Keep
Insertion sort is adaptive on nearly sorted data and has low overhead. Those properties make insertion-sort variants useful for small partitions inside hybrid sorts. It is not guaranteed to be the fastest for every small array; thresholds depend on implementation, element type, and hardware.
When Simple Is Right
The judgment: for large, random data, never reach for these — O(n²) on a million items is a trillion operations. But for small arrays (say under ~50 elements), nearly-sorted data, or when code simplicity and low memory matter more than asymptotics, insertion sort can genuinely win. This is the recurring quest theme one more time: the 'best' algorithm depends on the data and the scale, and dismissing a simple tool wholesale is as much an error as over-engineering with a fancy one.