Divide & Conquer · Sorting

Merge Sort Visualizer

What is Merge Sort

Split the array until every piece has one value, then merge those pieces back together. A merge walks two sorted runs and always takes the smaller head. The picture uses at most 6 values so each split and each choice stays visible.

5 2 4 1 3
1 2 3 4 5

Approach

Merge sort cuts the array in half, sorts each half the same way, then merges the two sorted halves. A single value is already sorted, so the splitting stops there.

SplitEach call keeps only the middle cut. The picture shows the current run and the two halves it came from.
MergeWalk both halves and always take the smaller head. Equal values come from the left half, so the sort stays stable.

Every level merges each value once, and there are about log n levels, so the work is n log n. The merge needs a second array of the same length.

Interactive solution

Split a run, then take the smaller head while merging
def merge_sort(a):
if len(a) <= 1: return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
if left head <= right head: take left
else: take right
copy leftover left
copy leftover right
return merged run
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(n log n)Every level merges n values, and the depth is log n.
Extra memoryO(n)The merge writes into a new run.

Implementation

def merge(left, right):
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

def merge_sort(a):
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    return merge(merge_sort(a[:mid]), merge_sort(a[mid:]))