Sorting algorithms
Sorting is one of the most studied problems in computer science, and one of the most useful: sorted data can be searched in O(log n), duplicates end up next to each other, and many problems become easy once the input is in order. This lesson builds the important algorithms and compares them.
In real code, use Python's built-in sorted() / list.sort(). They implement Timsort (now Powersort-based merging), a highly tuned hybrid of merge sort and insertion sort: O(n log n), stable, and very fast on partly sorted data.
The simple O(n²) sorts
They're slow on large inputs, but simple and good for understanding.
Insertion sort deserves respect: it's O(n) on nearly sorted data and the fastest choice for tiny arrays, which is why real-world sorts use it for small pieces.
Merge sort: divide and conquer
Split the list in half, sort each half recursively, then merge the two sorted halves:
There are log₂ n levels of halving, and each level merges n items in total: O(n log n) always, using O(n) extra memory.
Quicksort
Pick a pivot, move smaller items to its left and larger ones to its right (partition), then sort both sides recursively:
Average O(n log n) and in place, so very fast in practice. But a consistently bad pivot (say, always the first item of an already sorted list) degrades it to O(n²); a random pivot makes that vanishingly unlikely.
Counting sort: beating O(n log n)
Comparison-based sorts can't beat O(n log n). But if the values are small integers in a known range, you can count them instead of comparing:
O(n + k) for k possible values. Radix sort extends the idea to larger numbers digit by digit.
Comparing them
| Algorithm | Best | Average | Worst | Extra memory | Stable |
|---|---|---|---|---|---|
| Bubble / insertion | O(n) | O(n²) | O(n²) | O(1) | ✔ |
| Selection | O(n²) | O(n²) | O(n²) | O(1) | ✖ |
| Merge sort | O(n log n) | O(n log n) | O(n log n) | O(n) | ✔ |
| Quicksort | O(n log n) | O(n log n) | O(n²) | O(log n) | ✖ |
| Heapsort | O(n log n) | O(n log n) | O(n log n) | O(1) | ✖ |
| Counting sort | O(n + k) | O(n + k) | O(n + k) | O(k) | ✔ |
Timsort (sorted) |
O(n) | O(n log n) | O(n log n) | O(n) | ✔ |
Stability and sorting by keys
A stable sort keeps equal items in their original order. That lets you sort by several keys in steps, or rely on an earlier order:
Practice
- Sort a list of strings by length, and alphabetically among strings of the same length.
- Write
merge_intervals([[1, 3], [2, 6], [8, 10], [15, 18]])→[[1, 6], [8, 10], [15, 18]](sort first!). - Sort an array containing only 0s, 1s and 2s in one pass (the "Dutch national flag" problem).
1.What is merge sort's worst-case time complexity?
2.When does quicksort take O(n²)?
3.What does it mean for a sort to be stable?