Part IA Lent Term
Mergesort
Algorithm
Mergesort is a classic divide-and-conquer sorting algorithm:
- Divide: Split the array into two halves of (roughly) equal size.
- Conquer: Recursively sort each half.
- Combine: Merge the two sorted halves into a single sorted array.
Merge Procedure
Given two sorted subarrays and , use two pointers and :
- Initialise , (pointing to the start of each subarray).
- For to :
- If : place into output, increment .
- Else: place into output, increment .
- If one subarray is exhausted, copy the remainder of the other.
A common trick: append a sentinel to both subarrays so neither is ever exhausted before the loop ends.
Walkthrough Example
Input:
Split: [9, 10, 102, -7, 64, 18]
/ \
[9, 10, 102] [-7, 64, 18]
/ \ / \
[9] [10, 102] [-7] [64, 18]
(base) / \ (base) / \
[10] [102] [64] [18]
(base) (base) (base) (base)
Merge up: [9] + [10, 102] -> [9, 10, 102]
[64] + [18] -> [18, 64] (sorted merge)
[-7] + [18, 64] -> [-7, 18, 64]
[9, 10, 102] + [-7, 18, 64] -> [-7, 9, 10, 18, 64, 102]
Analysis
Recurrence
Let be the cost of sorting elements:
The term covers both the array copying for the subarrays and the merge comparison loop.
Closed Form via Substitution
Unwinding the recurrence:
After substitutions:
Via Master Theorem
, , . Compute . Since , Case 2 applies:
The Call Tree Method
At the top level, merge costs . At the next level, two merges each cost , totalling . Each of the levels contributes exactly , so .
Properties
| Property | Value |
|---|---|
| Worst case | |
| Average case | |
| Best case | |
| Stable | Yes — merge preserves order of equal keys |
| In-place | No (standard); extra space |
| Data-sensitive | No — always |
| Non-integer | , same solution |
Variations
- Bottom-up merge sort: Iterative, merging pairs of size 1, then 2, then 4, etc. Useful for linked lists where splitting is .
- Natural merge sort: Exploits existing runs (sorted subsequences) in the input; can approach on nearly-sorted data.
- In-place merge sort: The merge step can be made in-place with clever data movement, but the constant factor becomes large and practical implementations use the extra space.
Summary
| Aspect | Detail |
|---|---|
| Strategy | Divide and conquer |
| Recurrence | |
| Solution | |
| Master Theorem | Case 2: |
| Space | extra |
| Stable | Yes |
| Optimal | Yes — matches lower bound |