← back to stream

Sorting algorithms

In practice you almost never implement sorting — you call sort() and the language uses a well-tuned O(n log n) algorithm (usually Timsort in Python/JS, introsort in C++). What's worth knowing is which to pick when you do: Quicksort — fast average case, in-place, but worst-case O(n²) on adversarial input; Mergesort — guaranteed O(n log n), stable (preserves order of equal elements), but needs O(n) extra memory; Heapsort — O(n log n) guaranteed, in-place, no recursion, but slower in practice than quicksort; Timsort — a hybrid of mergesort and insertion sort that exploits already-sorted runs and wins on real-world data. Stability matters more than people think: if you sort by date, then by user, you want a stable sort so dates stay ordered within each user. Bubble sort is O(n²) and only useful as a teaching tool.