Best on a larger screen — the animation and controls have more room to breathe.
Inputs

Merge Sort

Merge sort is a divide-and-conquer sorting algorithm that splits the array in half, recursively sorts each half, and merges the two sorted halves by repeatedly taking the smaller front value. It guarantees O(n log n) time complexity in every case, uses O(n) auxiliary space, and is stable.

The core idea is that merging two already-sorted lists is much simpler than sorting an arbitrary list. Given two alphabetically ordered stacks of exam papers, you only compare the top sheet of each stack and take whichever comes first until both stacks are empty. Merge sort creates that condition by splitting the array down to single-element runs (which are already sorted) and merging pairs back upward.

How Merge Sort Works

The recursive sort(lo, hi) operates on one contiguous range. A range of zero or one element is already sorted and forms the base case. Otherwise it splits at mid = (lo + hi) // 2, recursively sorts the left half and the right half, and merges them.

The merge uses three indices: i points at the front of the left sorted run, j at the front of the right run, and k at the next free slot in the auxiliary array. While both runs have elements left, the smaller front value is copied to aux[k]. On a tie, the comparison arr[i] <= arr[j] takes the left value first, preserving the original relative order of equal keys and making the sort stable. When one run empties, the remaining elements of the other run drain into aux, and aux[lo..hi] is copied back into arr[lo..hi].

Merge Sort Step by Step

The default input is [38, 12, 56, 7, 12, 41, 23]. It includes two 12s, labeled 12a (index 1) and 12b (index 4), to show how stability preserves their order.

The recursion descends the left half first. [0..6] splits at mid 3 into [0..3] and [4..6]; [0..3] splits into [0..1] and [2..3]; [0..1] splits into the singletons [38] and [12a]. In the first merge, 38 > 12a takes the right value and drains 38, producing [12a, 38]. The same step on [2..3] compares 56 > 7 and gives [7, 56]. Merging those two runs interleaves them into [7, 12a, 38, 56], completing the left half.

The right half [12b, 41, 23] splits at mid 5. Singletons [12b] and [41] merge into [12b, 41], which then merges with [23]: take 12b, take 23 ahead of 41, and drain 41 to get [12b, 23, 41].

The final merge combines [7, 12a, 38, 56] with [12b, 23, 41]. After taking 7, the two fronts are 12a and 12b. Because <= selects the left run on equal values, 12a enters the buffer before 12b, keeping their original order. Next, 38 > 12b takes 12b, 38 > 23 takes 23, 38 ≤ 41 takes 38, 56 > 41 takes 41, and 56 drains. Copying back produces [7, 12a, 12b, 23, 38, 41, 56].

In the animation, the divide map at the top highlights the active range while the workbench below plays the current merge: the i and j pointers sit on the two run fronts, and each chosen value drops into the aux row one slot at a time before the result copies back. The tie beat in the final merge is labeled explicitly so you can see which 12 moves first.

Time and Space Complexity

CaseTimeSpace
BestO(n log n)O(n)
AverageO(n log n)O(n)
WorstO(n log n)O(n)

Each level of the recursion merges all n elements across its subproblems, and halving produces about log n levels, giving O(n log n) work regardless of input order. The tradeoff is the O(n) auxiliary buffer. The animated version is the standard top-down recursive form with a single reusable aux array.

Compared with quick sort, merge sort guarantees O(n log n) worst-case time and stability in exchange for O(n) extra memory.

Edge Cases

  • Empty or one-element array. Hits the base case and returns untouched.
  • Already sorted input. Performs the same splits and merges in O(n log n) time; merge sort is not adaptive and does not skip work on presorted input.
  • Reverse-sorted input. Takes the same O(n log n) time, with each merge taking from the right run first.
  • Duplicates. Equal values stay in their original relative order, as shown by the two 12s in the default input.
  • Odd-length ranges. Splitting at (lo + hi) // 2 gives the left half the extra element.

Common Mistakes

  • Using < instead of <= in the merge comparison. The output stays sorted, but ties favor the right run and break stability, a bug that tests on plain integers will not catch.
  • Forgetting the drain loops. After one run empties, the other's remaining values must still be copied; dropping them loses elements.
  • Copying back the whole aux instead of lo..hi. Slots outside the current range hold stale values from earlier merges.
  • Allocating a fresh buffer in every merge. Correct but wasteful; the standard form reuses one n-sized aux for the whole sort.
  • Returning after the two recursive calls but before merge. Each half ends up sorted while the combined array remains unsorted.

A few lessons that share the same technique or lead into the next idea.

Premium players need paid access. Every Explain doc is free.

Browse topic

Embed this lesson in a blog, docs, or course?

Found a mistake or something unclear?