0

Merge Sort

Medium

Split the array in half, sort each half recursively, then merge the two sorted runs in linear time.

divide and conquerstableO(n log n)
TimeO(n log n) always
SpaceO(n)
InputComma separated numbers
38
0
27
1
43
2
3
3
9
4
82
5
10
6

Divide until every piece has one element, then merge upward.

merges0writes0
1 / 40
sort(lo, hi):
if lo >= hi: return
mid = (lo + hi) / 2
sort(lo, mid); sort(mid+1, hi)
merge(lo, mid, hi)
merge: walk both halves, always taking the smaller front
Why it matters

Stable, predictable, and the basis for counting inversions and external sorting.

Keyboard
space play← → stepr restartctrl K search

More in Sorting

Next visualiser
Quick Sort