Merge Sort: Working, Example, and Complexity Analysis
Merge sort orders an array by repeatedly splitting it into smaller subarrays, sorting those subarrays, and combining them in sorted order. It is based on the divide-and-conquer paradigm.
The algorithm has three logical phases:
- Divide: Split the array into two approximately equal halves.
- Conquer: Recursively sort each half.
- Combine: Merge the two sorted halves into one sorted array.
The recursion stops when a subarray contains zero or one element because such a subarray is already sorted.
Merge sort is generally stable and has time complexity in the best, average, and worst cases. Standard array implementations use auxiliary space.
Footnotes
-
Merge sort - Overview, algorithm, stability, recurrence, and complexity characteristics. ↩ ↩2
-
Merge Sort - GeeksforGeeks - Algorithm steps, recurrence relation, and implementation details. ↩
Learn Merge Sort in 13 minutes
Core idea: merge two sorted arrays
The most important operation is the merge procedure.
Suppose the two sorted halves are:
- Left half:
- Right half:
Use one pointer for each half:
- Compare and ; copy .
- Compare and ; copy .
- Compare and ; copy .
- Compare and ; copy .
- Compare and ; copy .
- Copy the remaining .
Result:
Each element is examined at most a constant number of times during a merge, so merging two halves containing a total of elements takes time.
Footnotes
-
Merge Sort Algorithm - Divide-and-conquer analysis, Master Theorem solution, and space analysis. ↩
Merge Sort Process
- 1Step 1
Split the array into two halves. For an array of length , the halves contain approximately elements each.
- 2Step 2
Recursively divide each half until every subarray contains one element. A one-element subarray is the base case because it is already sorted.
- 3Step 3
Compare the first unprocessed element in each sorted subarray. Copy the smaller element into a temporary result array, then advance that subarray's pointer.
- 4Step 4
When one subarray is exhausted, copy all remaining elements from the other subarray. They are already sorted.
- 5Step 5
Merge progressively larger sorted subarrays until the complete array has been reconstructed in sorted order.
Worked example
Consider the input:
Because the input length is , the divisions are not perfectly equal, but the subarrays differ in size by at most one.
Division phase
The final one-element subarrays are:
Merge phase
Merge neighboring one-element arrays:
Now merge larger subarrays:
Finally:
Therefore, the sorted output is:
Why the merge is correct
Assume the left and right halves are already sorted.
At every iteration, the algorithm compares the smallest unprocessed element from each half. The smaller of these two elements must be the smallest element remaining overall:
- Every unprocessed element in the left half is at least as large as the left pointer.
- Every unprocessed element in the right half is at least as large as the right pointer.
- Therefore, choosing the smaller pointer value is safe.
This is a loop invariant: after each merge iteration, the output contains the smallest elements in sorted order. When one half is exhausted, all remaining elements in the other half are larger than or equal to the elements already copied, so appending them preserves sorted order.
By induction:
- One-element arrays are sorted.
- If two recursively sorted halves are merged correctly, their combined array is sorted.
- Therefore, the final array is sorted.
Using <= when values are equal causes the element from the left half to be selected first, preserving stability.
Footnotes
-
Merge Sort – Algorithm, Source Code, Time Complexity - Stability and merge implementation details. ↩
Key insight
Merge sort does not search for a favorable input arrangement. It always divides the data into halves and performs linear merging at each level, which makes its running time predictable.
Complexity calculation
Let denote the running time for sorting elements.
1. Divide cost
Finding the middle index and identifying the two subarrays takes constant time:
2. Recursive cost
The algorithm recursively sorts two subarrays, each of size approximately :
3. Merge cost
The merge operation processes all elements in the two halves:
Therefore, the recurrence is:
with the base case:
This recurrence is the standard merge-sort recurrence.2
Footnotes
-
Merge sort - Overview, algorithm, stability, recurrence, and complexity characteristics. ↩
-
Merge Sort Algorithm - Divide-and-conquer analysis, Master Theorem solution, and space analysis. ↩
Complexity calculation using a recursion tree
At each recursion-tree level, the total merge work is .
| Level | Number of subproblems | Size of each subproblem | Total merge work |
|---|---|---|---|
| or base-case work |
The height of the tree is:
Since each level contributes work and there are levels:
Thus:
The logarithm's base does not change the asymptotic class because:
The conversion factor is constant.
Complexity calculation using the Master Theorem
The Master Theorem analyzes recurrences of the form:
For merge sort:
- : two recursive subproblems
- : each subproblem has half the input size
- : merging takes linear time
Calculate:
Therefore:
This is the balanced case of the Master Theorem, which adds a logarithmic factor:
Hence, merge sort requires:
time in the best, average, and worst cases for the standard implementation.2
Footnotes
-
Merge Sort - GeeksforGeeks - Algorithm steps, recurrence relation, and implementation details. ↩
-
Merge Sort Algorithm - Divide-and-conquer analysis, Master Theorem solution, and space analysis. ↩
Asymptotic Time Comparison
Relative growth for representative input sizes; values are proportional to the stated complexity.
Space complexity
For an array implementation:
- The temporary merge array can hold up to elements: .
- The recursion stack has height .
- The total auxiliary space is:
Therefore:
The recursion stack alone is , but the temporary arrays dominate the space usage.
Complexity summary
| Property | Complexity |
|---|---|
| Best-case time | |
| Average-case time | |
| Worst-case time | |
| Auxiliary space for arrays | |
| Recursion-stack space | |
| Stability | Yes, when equal elements are taken from the left first |
| In-place in the standard array implementation | No |
A linked-list implementation can merge nodes with less auxiliary storage, while specialized in-place array variants exist but are more complicated and may have different practical performance characteristics.2
Footnotes
-
Merge Sort Algorithm - Divide-and-conquer analysis, Master Theorem solution, and space analysis. ↩
-
Merge sort - Overview, algorithm, stability, recurrence, and complexity characteristics. ↩
-
Time Complexity of Merge Sort - Comparison of time and space complexity with other sorting algorithms. ↩
Common misconception
The divide step is not the source of the n log n cost by itself. The logarithmic factor comes from the number of halving levels, while the linear factor comes from merging all elements at every level.
Important Questions and Edge Cases
Merge Sort Essentials
How to Analyze Merge Sort in an Exam
- 1Step 1
There are two calls on subproblems of size approximately , giving .
- 2Step 2
The merge scans all elements once, giving .
- 3Step 3
Use with .
- 4Step 4
Use a recursion tree or the Master Theorem. Here, , , and .
- 5Step 5
Because matches , the result is .
- 6Step 6
The temporary merge array contributes and the recursion stack contributes , so total auxiliary space is .
Knowledge Check
What is the main operation responsible for the linear work at each level of merge sort?
Explore Related Topics
Differentiating Divide & Conquer, Greedy Method, and Dynamic Programming
Understanding Belady's Anomaly in Operating Systems
Belady's Anomaly shows that, for some page‑replacement policies, adding more physical frames can increase the number of page faults.
- FIFO (a non‑stack algorithm) does not satisfy the inclusion property and can exhibit the anomaly.
- On the reference string , FIFO yields faults with frames but faults with frames.
- Stack algorithms such as LRU or Optimal obey , guaranteeing that more frames never raise fault counts.
- Designing a virtual‑memory system with stack‑based replacement eliminates Belady's Anomaly.
Complexity Analysis: Best Case, Worst Case, and Average Case
The material introduces best‑case, worst‑case, and average‑case complexity as three distinct functions describing an algorithm’s running time on inputs of size , explains how they are formally defined, and shows why worst‑case analysis is usually preferred.
- Best case: , the minimum time over all inputs of size .
- Worst case: , giving a guaranteed upper bound.
- Average case: , requiring an explicit input probability model.
- Linear search illustrates the three cases: best, worst, and average (expected comparisons).
- Worst‑case analysis is favored because it needs no probabilistic assumptions and ensures reliability for all inputs, especially in real‑time or safety‑critical systems.