Merge Sort Explained: Step-by-Step Trace, Complexity and Exam Questions
Follow Merge Sort from its inclusive-index pseudocode through a complete seven-element trace. Then revise its recurrence, stability, auxiliary space and common exam question forms.
KnowledgeGate Team
Exam prep & CS education

Merge Sort becomes testable when split ranges and merge comparisons are explicit. On [38, 27, 43, 3, 9, 82, 10], inclusive indices create a four-element left half, a three-element right half and 14 key comparisons. For GATE CS preparation, the useful habit is to write every subarray boundary, comparison and appended tail before deriving the recurrence and memory cost.
1. What Merge Sort Does and Why Divide and Conquer Works
Merge Sort is a comparison-based divide-and-conquer algorithm. It splits a range until every subarray contains one element, then merges adjacent sorted subarrays. A one-element array is already sorted, so it is the natural base case.
For an inclusive range [low..high], the three phases are precise:
Divide at
mid = floor((low + high) / 2).Recursively sort
[low..mid]and[mid+1..high].Combine the two sorted ranges using two pointers.
Merging two sorted lists is only the combine operation. Merge Sort creates those lists recursively. Other sorting methods may use swaps, partitions or heaps, so do not transfer their properties here.
Correctness follows by induction on range length. A zero-length or one-element range is sorted. For a longer range, the recursive calls sort both halves; during merge, the output prefix always contains the smallest consumed values in order, and appending the unexhausted tail preserves that order. Therefore the parent range is sorted.
2. Merge Sort Pseudocode: Indices, Base Case and Merge Rule
The algorithm uses zero-based indices and inclusive ranges:
mergeSort(A, low, high):
if low >= high:
return
mid = floor((low + high) / 2)
mergeSort(A, low, mid)
mergeSort(A, mid + 1, high)
merge(A, low, mid, high)
merge(A, low, mid, high):
left = copy of A[low..mid]
right = copy of A[mid + 1..high]
i = 0, j = 0, k = low
while i < length(left) and j < length(right):
if left[i] <= right[j]:
A[k] = left[i]
i = i + 1
else:
A[k] = right[j]
j = j + 1
k = k + 1
copy all remaining left values into A
copy all remaining right values into AThe <= branch takes the left item on equality, preserving stability. Both remainder loops matter because the main loop stops when either side is exhausted. Forget one, and elements disappear.
3. Worked Example: Sort [38, 27, 43, 3, 9, 82, 10] Step by Step
Start with indices 0..6, so mid = floor((0 + 6) / 2) = 3. The full split is:
[38, 27, 43, 3, 9, 82, 10]
├── [38, 27, 43, 3]
│ ├── [38, 27] -> [38] [27]
│ └── [43, 3] -> [43] [3]
└── [9, 82, 10]
├── [9, 82] -> [9] [82]
└── [10]Now merge upward. [38] + [27] needs one comparison and gives [27, 38]. [43] + [3] also needs one and gives [3, 43]. Merge those results by comparing 27 vs 3, 27 vs 43, then 38 vs 43. The left half becomes [3, 27, 38, 43] after three more comparisons, so its subtotal is 1 + 1 + 3 = 5.
On the right, [9] + [82] gives [9, 82] with one comparison. Merge [9, 82] + [10]: compare 9 vs 10 and take 9; compare 82 vs 10 and take 10; append 82. This gives [9, 10, 82], with a right-subtree subtotal of 1 + 2 = 3 comparisons.
The final merge makes every pick visible:
Compare
3 vs 9, take3.Compare
27 vs 9, take9.Compare
27 vs 10, take10.Compare
27 vs 82, take27.Compare
38 vs 82, take38.Compare
43 vs 82, take43.Append
82without another comparison.
The result is [3, 9, 10, 27, 38, 43, 82]. The total is 5 + 3 + 6 = 14 key comparisons. This count belongs to this input and trace because a merge may finish earlier for another input.
![Split-and-merge tree for [38, 27, 43, 3, 9, 82, 10] shows upward merges ending in [3, 9, 10, 27, 38, 43, 82].](https://cdn.knowledgegate.ai/blog-assets/blog_asset_1784460417604_janrpz.jpg)
![Two-pointer final-merge strip shows rows [3, 27, 38, 43] and [9, 10, 82], producing the sorted output through [3, 9, 10, 27, 38, 43, 82].](https://cdn.knowledgegate.ai/blog-assets/blog_asset_1784460418265_ycsk82.jpg)
4. Time Complexity: Derive It Instead of Memorising It
For a power-of-two input, each call creates two half-size problems and one linear merge:
T(n) = 2T(n/2) + Theta(n)
All merges at one level process n elements in total. There are log2 n split levels, giving Theta(n log n).
The standard implementation takes Theta(n log n) time in the best, average and worst cases. A sorted input does not make the baseline algorithm linear. A boundary check can skip some merges, but that is an implementation variation. If the notation feels compressed, revise time complexity and asymptotic notation before solving recurrences.
5. Stability, Extra Space and Implementation Choices
Stability is decided when equal keys meet during a merge. Suppose the left sorted half is [(2, original index 1), (4, index 0)] and the right sorted half is [(1, index 3), (4, index 2)]. After taking keys 1 and 2, the two key-4 records meet; <= selects the left record at index 0 before the right record at index 2, preserving their original order.
The cross-family comparison appears in Sorting Algorithms: Complexity, Stability, n log n Bound. Merge Sort questions add four algorithm-specific checks: the split tree, exact merge comparisons, left-on-equality tie rule and O(n) array buffer.
For arrays, the standard implementation uses O(n) auxiliary storage for merging and O(log n) recursion-stack depth. The O(n) merge buffer dominates, so overall auxiliary space is O(n). Standard array Merge Sort is not in-place.
A linked-list version can relink nodes instead of copying array elements. Recursion and implementation details still matter, so this does not justify a universal O(1) total-space claim.
6. Common Traps and How to Correct Them
Fragile base case:
low == highdoes not safely cover empty ranges. Uselow >= high.Overlapping recursive ranges:
[low..mid]and[mid..high]duplicatemidand may prevent termination. Use[low..mid]and[mid+1..high].False stability claim: choosing the right record when keys are equal can reverse equal-key order. Use
left[i] <= right[j]and take the left record.Damaged merge data: overwriting source values before comparing them can corrupt later decisions. Use safe temporary ranges or carefully managed storage.
Lost tail: after the comparison loop, copy the remainder from the unfinished side.
Wrong space answer:
O(log n)counts only recursive depth. Include the merge buffer, making the standard array answerO(n)auxiliary space.
7. How Exams Test Merge Sort
Exam questions usually vary one of four details: the array state after a named pass, the number of key comparisons, the recurrence, or a property such as stability and auxiliary space. Write down the implementation variant before calculating, because top-down recursion and bottom-up passes expose different intermediate states.
Apply bottom-up Merge Sort to [8, 3, 2, 9, 7, 1, 5, 4]. After width-1 merges, the array is [3, 8, 2, 9, 1, 7, 4, 5]. After width-2 merges, it is [2, 3, 8, 9, 1, 4, 5, 7]. This is the iterative variant, so do not confuse its passes with the earlier top-down tree.
Three fast checks are also worth knowing:
For
n = 8, a full top-down recursion tree has8leaves and15total calls when singleton calls are counted.The recurrence
2T(n/2) + nresolves toTheta(n log n).Merging sorted lists of lengths
mandnneeds at mostm + n - 1key comparisons.
Mixed time-complexity practice is most useful after writing out each recurrence. Merge Sort practice should combine top-down traces, bottom-up passes, recurrence solving and property checks.
8. A Final Merge Sort Check: Split, Count and Classify
Before accepting an answer, check three things: every recursive range shrinks, comparisons are counted only while both merge sides are non-empty, and stability and space are stated for the implementation shown. For the worked input, those checks produce [3, 9, 10, 27, 38, 43, 82] after 14 key comparisons, Theta(n log n) time and O(n) auxiliary array space.
Use DSA Using Java when the next task is implementing and testing the merge routine. Use GATE Guidance by Sanchit Sir when the next task is placing sorting inside the wider Algorithms sequence.
Keep learning
Bubble Sort Explained: Step-by-Step Trace, Complexity and Exam Traps
Trace bubble sort comparison by comparison, prove why it works, and learn how loop variants change operation counts, stability and best-case time.
Selection Sort Explained: Step-by-Step Trace, Complexity and Exam Traps
Learn the invariant behind Selection Sort, trace every pass, derive its exact comparison count, and avoid common stability and swap-count traps.
Merge Sort Interview Questions and Answers: Traces, Complexity, and Code
Prepare crisp merge sort interview answers through a fully traced array, boundary-safe Java implementation, complexity proof, stability example, and inversion-count follow-up.
Coding Questions for GATE CS: Trace Outputs and Complexity Step by Step
Learn a reliable way to solve coding output and complexity questions. Three fully traced C examples cover loops, mutation, recursion and operation counts.





