Sorting Algorithms (DSA #7)
Sorting is the most studied problem in computer science for a reason: it is the preprocessing step that makes everything else cheap. A sorted array unlocks binary search, enables two-pointer and greedy techniques, makes deduplication trivial, and turns many “compare all pairs” problems into “compare neighbours”. Learn the handful of sorts below and you also learn the templates for divide-and-conquer, partitioning, and heaps.
This chapter covers the quadratic sorts, the two \(O(n \log n)\) workhorses (merge and quick), heap sort, counting sort, and the properties — stability, in-place, worst case — that decide which to use.
What makes a sort “good”
Four properties decide the choice:
- Time complexity — average and worst case.
- Space — does it need an auxiliary array?
- Stability — do equal elements keep their original relative order? Important when sorting by multiple keys.
- In-place — does it reorder within the input array?
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble | \(O(n)\) | \(O(n^2)\) | \(O(n^2)\) | \(O(1)\) | yes |
| Selection | \(O(n^2)\) | \(O(n^2)\) | \(O(n^2)\) | \(O(1)\) | no |
| Insertion | \(O(n)\) | \(O(n^2)\) | \(O(n^2)\) | \(O(1)\) | yes |
| Merge | \(O(n \log n)\) | \(O(n \log n)\) | \(O(n \log n)\) | \(O(n)\) | yes |
| Quick | \(O(n \log n)\) | \(O(n \log n)\) | \(O(n^2)\) | \(O(\log n)\) | no |
| Heap | \(O(n \log n)\) | \(O(n \log n)\) | \(O(n \log n)\) | \(O(1)\) | no |
| Counting | \(O(n+k)\) | \(O(n+k)\) | \(O(n+k)\) | \(O(k)\) | yes |
The \(O(n \log n)\) bound is not an accident: any comparison sort needs at least \(\log_2(n!)\) comparisons, which is \(\Theta(n \log n)\). To beat it you must stop comparing — counting/radix sort do.
The quadratic sorts
Bubble sort repeatedly swaps adjacent out-of-order pairs. Educational, rarely used.
def bubble(a):
n = len(a)
for i in range(n):
swapped = False
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped: # already sorted -> O(n) best case
break
return a
Insertion sort builds a sorted prefix, inserting each new element where it belongs. Its \(O(n)\) best case on nearly sorted data makes it the practical choice for small arrays (and the base case inside merge/quick sorts).
def insertion(a):
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key: # shift larger elements right
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.62cm, minimum height=0.6cm, font=\small\bfseries}]
\foreach \v [count=\i from 0] in {5,2,4,6,1,3} {
\node[c, fill=blue!10] at (\i*0.68,0) {\v};
}
\draw[thick, green!50!black] (-0.34,-0.42) rectangle (0.34,0.42);
\node[font=\scriptsize\ttfamily, text=green!50!black, anchor=north] at (0,-0.6) {sorted prefix};
\node[font=\scriptsize\ttfamily, text=orange!75!black, anchor=north] at (0.68,-0.6) {insert next};
\end{tikzpicture}
Selection sort finds the minimum of the unsorted suffix and swaps it to the front. Always \(O(n^2)\), but it makes at most \(n\) swaps, which can matter when writes are expensive.
def selection(a):
for i in range(len(a)):
m = i
for j in range(i + 1, len(a)):
if a[j] < a[m]:
m = j
a[i], a[m] = a[m], a[i]
return a
Merge sort: divide, sort, merge
Merge sort splits the array in half, sorts each half recursively, and merges the two sorted halves. The merge is the two-pointer routine from Chapter 3.
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
return merge(left, right)
def merge(a, b):
out, i, j = [], 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]: # <= keeps it stable
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
out.extend(a[i:]); out.extend(b[j:])
return out
The recurrence \(T(n) = 2T(n/2) + O(n)\) resolves to \(O(n \log n)\) (Chapter 24). Merge sort is stable and predictable, but needs \(O(n)\) auxiliary space.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.58cm, minimum height=0.55cm, font=\scriptsize\bfseries}]
\foreach \v [count=\i from 0] in {5,2,4,6,1,3} { \node[c, fill=blue!10] at (\i*0.64,0) {\v}; }
\foreach \v [count=\i from 0] in {5,2,4} { \node[c, fill=orange!18] at (\i*0.64,-0.8) {\v}; }
\foreach \v [count=\i from 0] in {6,1,3} { \node[c, fill=green!18] at (2.0+\i*0.64,-0.8) {\v}; }
\foreach \v [count=\i from 0] in {2,5} { \node[c, fill=orange!18] at (0+\i*0.64,-1.6) {\v}; }
\node[c, fill=orange!18] at (1.28,-1.6) {4};
\foreach \v [count=\i from 0] in {1,6} { \node[c, fill=green!18] at (2.0+\i*0.64,-1.6) {\v}; }
\node[c, fill=green!18] at (3.28,-1.6) {3};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (1.6,-2.2) {split to singletons, then merge sorted runs};
\end{tikzpicture}
Quick sort: partition and recurse
Quick sort picks a pivot, partitions the array so smaller elements are left and larger are right, then recurses on both sides. In-place and fast, but a bad pivot (already-sorted input with the first element as pivot) gives \(O(n^2)\).
def quick_sort(a, lo=0, hi=None):
if hi is None:
hi = len(a) - 1
if lo >= hi:
return a
p = partition(a, lo, hi)
quick_sort(a, lo, p - 1)
quick_sort(a, p + 1, hi)
return a
def partition(a, lo, hi):
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i] # pivot into place
return i
The fix for the worst case is to randomize the pivot, making the expected time \(O(n \log n)\) regardless of input order. The partition routine is itself reusable — quickselect (Chapter 24) finds the \(k\)-th smallest in average \(O(n)\) using the same idea.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.62cm, minimum height=0.6cm, font=\small\bfseries}]
\foreach \v/\col [count=\i from 0] in {3/blue,1/orange,4/green,1/blue,5/orange,9/green,2/blue} {
\node[c, fill=\col!18] at (\i*0.68,0) {\v};
}
\node[c, fill=red!25, very thick] at (4*0.68,0) {5};
\node[font=\rmfamily\small, text=black!60, anchor=north] at (2.4,-0.6) {pivot 5: smaller left, larger right, then recurse};
\end{tikzpicture}
Heap sort and counting sort
Heap sort builds a max-heap and repeatedly moves the max to the end. It is \(O(n \log n)\) worst case and in-place, at the cost of poor cache locality and instability (Chapter 11 builds the heap).
import heapq
def heap_sort(a):
heapq.heapify(a) # O(n)
return [heapq.heappop(a) for _ in range(len(a))] # O(n log n)
Counting sort beats the comparison bound when the key range \(k\) is small: count occurrences, then write them back in order.
def counting_sort(a):
if not a: return a
counts = [0] * (max(a) - min(a) + 1)
offset = min(a)
for x in a:
counts[x - offset] += 1
out, i = [], 0
for x, c in enumerate(counts):
out.extend([x + offset] * c)
return out
It is \(O(n + k)\) time and not comparison-based, which is how it sidesteps the \(\Theta(n \log n)\) lower bound. Radix sort applies it digit by digit for large integer ranges.
Which sort should you reach for?
- In Python, just use
sorted()/list.sort()— Timsort, a stable hybrid of merge and insertion, \(O(n \log n)\) worst case and fast on real data. - Need stability? Merge sort or Timsort.
- Memory constrained? Heap sort or quick sort.
- Values in a small integer range? Counting sort, \(O(n + k)\).
- Nearly sorted input? Insertion sort is \(O(n)\).
Pitfalls
- Picking a bad quick-sort pivot. First/last element on sorted input is \(O(n^2)\); randomize.
- Assuming stability. Selection and quick sort are not stable; sorting by one key can scramble another.
- Extra space in “in-place” claims. Merge sort is not in-place; quick sort’s recursion uses \(O(\log n)\) stack.
- Sorting when hashing suffices. If you only need to group/count, a hash map is \(O(n)\) versus \(O(n \log n)\).
- Overflow in counting sort. The range \(k\) can be huge (e.g. 32-bit ints); counting sort then allocates too much memory.
Why can no comparison sort beat \(O(n \log n)\)? When is quick sort’s worst case triggered and how do you avoid it?
ASolution
A comparison sort must distinguish \(n!\) possible orderings using binary decisions, requiring at least \(\log_2(n!) = \Theta(n \log n)\) comparisons. Quick sort degrades to \(O(n^2)\) when the pivot splits off one element at a time, e.g. always choosing the first element on sorted input; randomizing the pivot makes that unlikely and gives expected \(O(n \log n)\).
Next: Searching Algorithms (DSA #8) — once sorted, find in logarithmic time.