Merge Sort and Sorted Runs
During a merge, compare the front of each sorted run before taking the next element.
Core Intuition & How It Works
Merge sort divides an array in half recursively until single-element runs remain, then merges sorted halves in linear time. It guarantees O(n log n) worst-case runtime and preserves the relative order of equal keys (stability).
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n log n) guaranteed |
| Space Complexity | O(n) array, O(log n) linked list |
| Topic Chapter | Chapter 9: Sorting & Selection |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Break ties in favor of the left half (left[i] <= right[j]) during the merge step to guarantee sort stability.
Common Pitfalls & Edge Cases
Allocating a new temporary buffer inside every recursive call instead of reusing one O(n) auxiliary buffer.
Real-World & Technical Interview Applications
External disk sorting, linked-list sorting, inversion counting, and stable standard library sorts (Timsort).