Sub topic 11
Merge Sort
This chapter assumes you can read recursion, know the recurrence T(n) = 2T(n/2) + cn and the Master theorem from earlier chapters, and understand stability and in-place sorting. It covers how merge sort works, why it costs Θ(n log n) in every case, and the properties GATE questions test.
The Idea: Divide, Conquer, Combine
Merge sort has three steps:
- Divide. Split the array into two halves at the midpoint.
- Conquer. Sort each half recursively. An array of length 0 or 1 is already sorted, so this is the base case.
- Combine. Merge the two sorted halves into one sorted array.
The work is in the merge step. Two sorted lists can be merged in one pass. Keep one index in each list, compare the two front elements, and move the smaller one to the output.
The Code
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
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))The output is [3, 9, 10, 27, 38, 43, 82].
Two details matter:
- The test
left[i] <= right[j]takes from the left half on a tie. Equal keys keep their original order, so the sort is stable. - After the loop, one half is used up.
extendcopies the leftover tail of the other half, which is already sorted and no smaller than anything placed so far.
Tracing the Merge
Merge [3, 27, 38, 43] and [9, 10, 82].
| Step | Compare | Output so far |
|---|---|---|
| 1 | 3 vs 9 | 3 |
| 2 | 27 vs 9 | 3, 9 |
| 3 | 27 vs 10 | 3, 9, 10 |
| 4 | 27 vs 82 | 3, 9, 10, 27 |
| 5 | 38 vs 82 | 3, 9, 10, 27, 38 |
| 6 | 43 vs 82 | 3, 9, 10, 27, 38, 43 |
| tail | right has 82 left | 3, 9, 10, 27, 38, 43, 82 |
This merge makes 6 comparisons for 7 elements. Each comparison places exactly one element, and the tail is copied without comparing.
Recursion Structure
The tree has about log₂ n levels. Splitting costs almost nothing in the pseudocode version. Merging at any one level touches every element once, so each level costs Θ(n) in total.
Deriving the Time Complexity
Let T(n) be the time to sort n elements. The two recursive calls each handle n/2 elements. The merge does at most n − 1 comparisons and n moves, which is Θ(n). So:
T(n) = 2T(n/2) + Θ(n), with T(1) = Θ(1).
By the Master theorem. Here a = 2, b = 2 and f(n) = Θ(n). Compare f(n) with n^(log_b a) = n^(log₂ 2) = n. They have the same growth, so case 2 applies and T(n) = Θ(n log n).
By the recursion tree. Level k has 2^k subproblems of size n/2^k. Each level costs 2^k · c · n/2^k = cn. There are log₂ n + 1 levels, so the total is cn(log₂ n + 1) = Θ(n log n).
The result holds for the best, average and worst case. The merge always scans all elements, whatever order they arrive in. Merge sort is therefore not adaptive in its basic form.
Comparison Count
The number of comparisons is more precise than the Θ bound.
- Worst case: n⌈log₂ n⌉ − 2^⌈log₂ n⌉ + 1, which is about n log₂ n − n. This occurs when the merges alternate between the halves.
- Best case: about (n/2) log₂ n. This occurs when every element of one half is smaller than every element of the other. Each merge then stops comparing as soon as one half is exhausted, after n/2 comparisons.
Both counts are Θ(n log n), so the time is Θ(n log n) in all cases. A GATE question may ask for the maximum number of comparisons when merging lists of sizes m and n. The answer is m + n − 1.
Space Complexity
Merging needs an auxiliary buffer of up to n elements, so the extra space is O(n). The Python version above also creates slices, but the total live memory is still O(n) plus the recursion stack of depth O(log n).
Merge sort is not in-place in its standard array form. In-place merging algorithms exist, but they are complicated and slower in practice, so exam answers treat merge sort as using O(n) extra space.
Merge Sort on Linked Lists
Merge sort suits linked lists well. Merging needs only pointer changes, not an extra array, so it uses O(1) auxiliary space for the merge. Finding the middle takes a slow/fast pointer pass. Quick sort and heap sort depend on random access, so they do poorly on linked lists. Merge sort is the usual choice there.
Comparison with Other Sorts
| Algorithm | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Merge sort | n log n | n log n | n log n | O(n) | Yes |
| Quick sort | n log n | n log n | n² | O(log n) | No |
| Heap sort | n log n | n log n | n log n | O(1) | No |
| Insertion sort | n | n² | n² | O(1) | Yes |
Merge sort is the only entry here that combines a guaranteed n log n worst case with stability. Its cost is the extra memory.
Common Errors
- Using
<instead of<=in the merge. The result is still sorted, but ties are taken from the right half first, so the sort loses stability. - Saying the best case is O(n). Insertion sort has an O(n) best case. The basic merge sort does not, since it always divides and merges.
- Forgetting the tail copy. If you drop the two
extendcalls, elements are lost whenever one half empties first. - Computing the midpoint wrongly in index-based versions. With
loandhi, usemid = lo + (hi - lo) // 2. In fixed-width integer languages,(lo + hi) / 2can overflow. - Treating the merge as O(1) or O(log n). It is Θ(n). Using the wrong merge cost changes the recurrence and the answer.
- Confusing the depth with the total work. The recursion depth is log n, but the work at each level is n.
A Variation: Unequal Splits
Suppose a variant splits the array into parts of size n/3 and 2n/3, with a linear merge. The recurrence is T(n) = T(n/3) + T(2n/3) + cn. The Master theorem does not apply, since the subproblem sizes differ. Use a recursion tree instead. The longest path follows the 2n/3 branch and has log_{3/2} n levels. Every full level costs at most cn, so T(n) = O(n log n). Because the shallowest path still has log₃ n levels, the bound is tight: Θ(n log n). The base of the logarithm changes only a constant factor.
Bottom-Up Merge Sort
Recursion is not required. Bottom-up merge sort merges runs of size 1 into runs of size 2, then 4, then 8, and so on, until one run covers the array.
def merge(a, lo, mid, hi):
left = a[lo:mid]
right = a[mid:hi]
i = j = 0
k = lo
while i < len(left) and j < len(right):
if left[i] <= right[j]:
a[k] = left[i]
i += 1
else:
a[k] = right[j]
j += 1
k += 1
while i < len(left):
a[k] = left[i]
i += 1
k += 1
while j < len(right):
a[k] = right[j]
j += 1
k += 1
def merge_sort_bottom_up(a):
n = len(a)
width = 1
while width < n:
for lo in range(0, n, 2 * width):
mid = min(lo + width, n)
hi = min(lo + 2 * width, n)
merge(a, lo, mid, hi)
width *= 2
return a
print(merge_sort_bottom_up([5, 2, 4, 7, 1, 3, 2, 6]))The output is [1, 2, 2, 3, 4, 5, 6, 7]. The outer loop runs ⌈log₂ n⌉ times, and each pass is Θ(n). The total is Θ(n log n) with no recursion stack.
Summary of Facts to Memorize
- Recurrence:
T(n) = 2T(n/2) + Θ(n), so T(n) = Θ(n log n) in all cases. - Merging two sorted lists of sizes m and n takes at most m + n − 1 comparisons.
- Extra space is O(n) for arrays. Merge sort is not in-place.
- It is stable when ties are taken from the left half.
- It is a strong choice for linked lists and for external sorting, where data is read sequentially.
Exercise
A merge sort variant splits an array of n elements into halves, but its merge step takes Θ(n²) time. What is the solution of the resulting recurrence?
Show answer
The recurrence is T(n) = 2T(n/2) + Θ(n²). Here a = 2, b = 2, so n^(log_b a) = n. Since f(n) = n² grows polynomially faster than n (and the regularity condition 2(n/2)² = n²/2 ≤ c·n² holds with c = 1/2), case 3 applies and T(n) = Θ(n²). The merge dominates the cost.
Exercise
Two sorted lists contain 8 and 5 elements. What is the maximum number of comparisons a standard merge makes, and what is the minimum?
Show answer
The maximum is 8 + 5 − 1 = 12, which happens when the lists interleave so that neither is exhausted until the last comparison. The minimum is min(8, 5) = 5. This happens when every element of the 5-element list is smaller than every element of the other list, so the shorter list is exhausted after 5 comparisons.
Exercise
Merge sort is run on the records (2, a), (1, b), (2, c), (1, d), sorted by the number only. What order do the letters appear in when ties are taken from the left half? What changes if ties are taken from the right half?
Show answer
With ties taken from the left half, the output is (1, b), (1, d), (2, a), (2, c), so the letters read b, d, a, c. Equal keys keep their input order, so the sort is stable. If ties are taken from the right half, the output is (1, d), (1, b), (2, c), (2, a), which reverses the order of equal keys and is not stable.