Sorting Algorithms
A sorting algorithm repeatedly strengthens an order guarantee. Different algorithms spend comparisons, writes and auxiliary memory differently.
Picture the idea
Sorting cards in your hand extends a tidy prefix. Merging two already ordered queues only requires comparing the people at their fronts.
When to use it
Sort when ordering reveals duplicate runs, nearest candidates, a monotone predicate or a useful greedy choice.
How it works
In insertion sort, save the next item, shift larger earlier items right and fill the gap. The prefix ending at the inserted item is now sorted.
- Compare an adjacent pair.
- Swap or shift values.
- Merge ordered runs.
- Partition around a pivot.
Insertion sort costs O(n²) in the worst case and O(n) on an already sorted sequence. Standard merge sort uses O(n log n) time and O(n) auxiliary storage for arrays.
Watch for this mistake
A stable merge must take the left item first when keys tie.
Discuss stability when records with equal keys have meaningful original order.