Lesson 49 of 86IntermediatePro Interactive Lesson

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

MetricComplexity
Time ComplexityO(n log n) guaranteed
Space ComplexityO(n) array, O(log n) linked list
Topic ChapterChapter 9: Sorting & Selection
Difficulty LevelIntermediate

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).

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.