DSA AnimatorDSA animations
Merge Sort LC #912 Medium Divide & Conquer · Merge
Problem

Given an array of integers nums, sort the array in ascending order using the Merge Sort algorithm — recursively split the array in half until each piece is a single element (trivially sorted), then merge sorted pairs back together in linear time.

Example 1
Input: nums = [8,4,3,7,6]
Output: [3,4,6,7,8]
Constraints: 1 ≤ n ≤ 5*10^4  |  -5*10^4 ≤ nums[i] ≤ 5*10^4
Try Examples
Custom:
Approach
Divide, Conquer, Merge
Split the array in half recursively until every piece is a single element, then merge sorted pairs back together with one linear scan per merge. O(n log n) time in the best, average, AND worst case — O(n) space for the auxiliary merge buffer.
Array
Comparing Smaller (winner) Just placed Sorted
Variables
range
—
depth
—
comparisons
0
writes
0
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
If the range has ≤1 element, it's already sorted
2
Split the range at the midpoint into two halves
3
Recursively sort each half
4
Merge the two sorted halves back together by repeatedly taking the smaller front element
Best
O(n log n)
Avg/Worst
O(n log n)
Space
O(n)
Why It Works

Merging two already-sorted sequences takes only O(n) — a single linear scan that compares the fronts of each side and copies the smaller one across. There are O(log n) levels of splitting (each level halves the range), so total work is O(n log n) — in the best, average, and worst case alike, unlike Quick Sort's adversarial O(n²). Merge Sort is also stable (the left[i] <= right[j] tie-break keeps equal elements in their original relative order) but not in-place — every merge needs an auxiliary buffer to hold a snapshot of both halves before overwriting them, which is the classic time/space tradeoff versus Quick Sort's O(log n) average auxiliary space.

How to solve Merge Sort

LeetCode 912 · Medium · Sorting Algorithms · Pattern: Divide and Conquer

Why the obvious approach is slow

Quadratic sorts are fine for small inputs only. Merge sort splits the work in half again and again.

The key idea

Split the array into two halves. Sort each half recursively, until a part has only one element, which is already sorted. Then merge two sorted halves, by repeatedly taking the smaller front element. Merging two parts costs time proportional to their total length. There are log n levels of halving, so the total is O(n log n).

Remember

Split, sort halves, merge by taking the smaller front. Guaranteed O(n log n), at the cost of extra memory.

Run the animation above on your own input, or watch the 1:41 video explanation of Merge Sort with a dry run and Java code.

More Sorting Algorithms problems