1.Merge sort — O(n log n), stable, extra space
Merge sort splits the array in half, recursively sorts each half, then merges the two now-sorted halves back together — the same two-pointer merge from Two Pointers, applied recursively.
Key features
- O(n log n) in EVERY case (best, average, worst) — unlike quicksort, its performance does not depend on the input's arrangement
- Needs O(n) extra space for the merged output at each level — it does not sort in place, unlike quicksort
- Stable, but only if the merge step uses <= (not <) when comparing — see the mistake below
Merge sort is O(n log n) unconditionally, at the cost of O(n) extra space — and its comparison must use <=, not <, to actually keep the stability the algorithm is known for.