Sub topic 10
Merge Sort
Assume you know arrays, recursion, logarithms, and basic recurrence notation. Merge sort is a divide-and-conquer algorithm: it divides an array into smaller parts, solves each part recursively, and combines the sorted results.
The Working Model
Merge sort has two stages:
- Split the array into two halves until every part contains at most one element.
- Merge neighboring sorted parts by repeatedly choosing the smaller front element.
A one-element array is already sorted. During a merge, each element is examined at most once for each level of recursion, so merging two parts of total size \(n\) takes \(\Theta(n)\) time.
The running-time recurrence is
\[ T(n) = 2T(n/2) + \Theta(n). \]
There are two recursive subproblems, each of size \(n/2\), and a linear-time merge. The Master theorem gives
\[ T(n) = \Theta(n\log n). \]
This bound applies to the best, average, and worst cases. Unlike quick sort with an unlucky pivot, merge sort does not become quadratic because its split is fixed.
Implementation and Stability
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
out = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
out.extend(left[i:])
out.extend(right[j:])
return out
values = [8, 3, 5, 1, 3]
print(merge_sort(values)) # [1, 3, 3, 5, 8]When equal values occur, the condition left[i] <= right[j] takes the element from the left half first. If the elements contain records with a secondary field, this preserves their original relative order. Such a sorting algorithm is called stable.
The slicing and output list use \(\Theta(n)\) additional space at each merge level in this implementation. The total auxiliary space is \(\Theta(n)\), excluding the recursion stack. Merge sort is therefore stable, predictable, and usually not in-place.
Comparison Table
| Property | Merge sort |
|---|---|
| Best, average, worst time | \(\Theta(n\log n)\) |
| Extra space | \(\Theta(n)\) in this implementation |
| Stable | Yes |
| In-place | Usually no |
| Adaptive | Generally no |
Exercise
For n = 16, how many merge levels does merge sort have, and what is the total merge work per level?
Show answer
It has log₂(16) = 4 levels. Each level processes all 16 elements, so the merge work is Θ(16) per level and Θ(16 log₂ 16) overall.