Comparison Sorts
Sorts that only compare pairs of elements, such as insertion sort and quicksort.
- Problem: Sorting
- Reorder elements so that their keys are in non-decreasing order under a given comparator.
- Input: A sequence a[0..n-1] of items. Each item has a key. Keys are compared by a total preorder, so equal keys are allowed.
- Output: A permutation of the input in which key(a[i]) <= key(a[i+1]) for every i.
- Constraints
- Model: comparisons only, or access to key digits. Comparison sorts need Ω(n log n) comparisons in the worst case.
- Stability: items with equal keys keep their input order.
- Space: in place, O(log n) stack, or an O(n) buffer.
- Input shape: random, nearly sorted, reversed, many duplicates, or a small integer range.
- Memory model: everything fits in RAM, or data lives on disk or on many machines.
- Cost: comparisons, writes or cache misses.
- Guarantee: a worst-case bound, or a good average case.
- Main idea
- Decide the order only by asking whether a < b. Any such sort needs at least log₂(n!) comparisons in the worst case, which is about n log₂ n.
Insertion Sortalgorithm
Build a sorted prefix one element at a time by sliding each new key left into place. Simple, stable, in-place and fast on nearly sorted data.
Binary Insertion Sortalgorithm
Insertion sort that finds each key's slot with binary search. It needs about n log n comparisons, but it still shifts up to n²/2 values.
Selection Sortalgorithm
Repeatedly pick the smallest remaining value and swap it to the front. Always n(n − 1)/2 comparisons, but at most n − 1 swaps.
Bubble Sortalgorithm
Compare neighbours and swap them when they are out of order. Each pass bubbles the largest value to the end. Simple to teach, rarely the right choice.
Shell Sortalgorithm
Insertion sort on values that are a gap apart, with a shrinking gap. Early passes move keys far, so the last pass finds nearly sorted data.
Merge Sortalgorithm
Split the array in halves, sort each half, then merge the two sorted runs. Always O(n log n) and stable, at the cost of a buffer.
Quicksortalgorithm
Pick a pivot, split the rest into smaller and larger values, and sort both parts recursively. Fast on average. The in-place version needs almost no extra memory.
Heap Sortalgorithm
Build a max-heap inside the array, then repeatedly swap the maximum behind the heap. O(n log n) in the worst case with O(1) extra space.