Card 11/ 11

RecapDifficulty: Intermediate2 min

Recap: Elementary Sorting

Three ways to grow a sorted part, their counts on each input, and the one that adapts.

Elementary sorting comes down to the nine ideas below, each listed with the card that covers it. One picture holds them together: every member grows a sorted part by one item per pass, and what tells the three apart is where that item comes from and how far it moves.

What the topic established, and which card it was on
The ideaWhere
All three grow a sorted part one item per pass; stable, in place and adaptive are the properties that tell sorts apartElementary Sorts: Growing a Sorted Part One Item at a Time
Bubble sort carries the largest unsorted item right by swapping neighbours, one swap per inversion, and stops after a pass with no swapsBubble Sort: Swapping Neighbours Until Nothing Moves
The swapped flag is the whole early exit; TypeScript's sort() with no comparator compares numbers as textBubble Sort in Python, Java and TypeScript
Selection sort scans for the smallest remaining item: n(n − 1)/2 comparisons on every input, at most n − 1 swaps, and not stableSelection Sort: Taking the Smallest of What Remains
Only selection sort's swap count changes with the input; Heapsort replaces its scan with a heapSelection Sort in Python, Java and TypeScript
Insertion sort shifts larger items right to open a gap, one shift per inversion, so nearly sorted input costs close to O(n)Insertion Sort: Sliding Each Item Into Place
Stopping at an item equal to the key keeps insertion sort stable; bisect.insort finds the place in O(log n) but still shiftsInsertion Sort in Python, Java and TypeScript
On the same inputs the counts separate the three, and library sorts keep insertion sort for short runsBubble vs Selection vs Insertion Sort
Without the no-swap check, bubble sort makes n(n − 1)/2 comparisons even on sorted inputExpecting an O(n) Best Case From a Bubble Sort Without the Early Exit

The costs to keep are these, for an array of n items.

The three elementary sorts at a glance, on n items
SortBest caseWorst caseMost movesStable
Bubble sortO(n), with the early exitO(n²)n(n − 1)/2 swapsYes
Selection sortO(n²)O(n²)n − 1 swapsNo
Insertion sortO(n)O(n²)n(n − 1)/2 shiftsYes

Together they let you trace each elementary sort by hand, count its comparisons and moves on a given input, write it in Python, Java and TypeScript, and pick insertion sort when the data is small or nearly sorted.