Overview & Concept
Merge Sort is a classic Divide-and-Conquer sorting algorithm invented by John von Neumann. It recursively splits the array into two halves until single-element subarrays are reached, then merges the sorted halves back together in linear time, guaranteeing O(n log n) worst-case time complexity.
How It Works
Divide: Recursively split array at midpoint into left and right halves.
Conquer: Base case is reached when subarray size is 1 (trivially sorted).
Combine (Merge): Two sorted subarrays are merged into a single sorted buffer using two pointer comparisons.
Stability Guaranteed: Equal elements from the left subarray are always chosen first during merge.
Step-by-Step Execution
Asymptotic Complexity Analysis
| Metric | Best Case | Average Case | Worst Case | Space Complexity |
|---|---|---|---|---|
| Complexity Bound | O(n log n) | O(n log n) | O(n log n) | O(n) |
| Explanation | Optimal input arrangement minimizing operations. | Expected time for uniformly distributed randomized inputs. | Adversarial degenerate conditions requiring full traversal. | Auxiliary memory allocated beyond original input size. |
Pseudocode & Invariants
procedure mergeSort(A, left, right):
if left >= right: return
mid = floor((left + right) / 2)
split into A[left..mid] & A[mid+1..right]
mergeSort(A, left, mid); mergeSort(A, mid + 1, right)
merge(left, mid, right):
compare left[i] and right[j]
place smaller into merged A[k]
copy remaining elements
return A- Subarray Sortedness: After merge(low, mid, high), the subarray A[low..high] is strictly sorted.
Advantages & Disadvantages
Key Advantages
- •Guaranteed O(n log n) time complexity in all cases (best, average, worst).
- •Stable sorting: preserves original ordering of duplicate keys.
- •Predictable performance with zero worst-case degradation.
- •Excellent for external sorting of files that exceed available RAM.
Trade-offs & Limitations
- •Requires O(n) auxiliary memory for temporary merge buffers.
- •Higher constant factors than Quick Sort for in-memory primitive arrays.
Real-World Applications
External File Sorting
Sorting terabyte-scale datasets on disk by sorting chunks and performing multi-way merges.
Standard Library Stable Sorting
Java Object sorting and Python Timsort (derived from Merge Sort).
Decision Guide: When to Use
Ideal Scenarios
- ✓When stable sorting is strictly required.
- ✓When worst-case O(n log n) guarantees are essential.
- ✓When sorting linked lists or disk-resident files.
Consider Alternatives When
- ✕When auxiliary memory is tightly constrained and O(1) in-place sorting is required.
Explore Related Algorithms
Compare trade-offs and complexity across complementary tools in AlgoViz.