Loading controls...
Loading visualization...
Time: O(n log n)
Space: O(n)

Legend

Comparing
Elements being compared
Swapping
Elements being swapped
Sorted
Elements in final position
Unsorted
Elements not yet processed
How to read the visualization:
  • • Numbers show element values
  • • Bottom labels show array indices
  • • Colors indicate current operation
  • • Height represents value magnitude

Inspector

No active frame to inspect

Reference implementation of Merge Sort. Select a language tab to view and copy the code.

def merge_sort(arr: list[int]) -> None:
    if len(arr) <= 1:
        return
    mid = len(arr) // 2
    left, right = arr[:mid], arr[mid:]
    merge_sort(left)
    merge_sort(right)

    i = j = k = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            arr[k] = left[i]; i += 1
        else:
            arr[k] = right[j]; j += 1
        k += 1
    while i < len(left):
        arr[k] = left[i]; i += 1; k += 1
    while j < len(right):
        arr[k] = right[j]; j += 1; k += 1

Python — Code Walkthrough

  1. In-place variant using slices

    left, right = arr[:mid], arr[mid:]

    Python slice notation creates new list copies for the left and right halves. The function sorts them recursively then merges back into the original arr by index assignment.

  2. Base case — len <= 1

    if len(arr) <= 1: return

    A list of 0 or 1 elements is already sorted; return immediately. This is the recursion termination condition.

  3. Three-pointer merge

    i = j = k = 0

    i scans the left half, j scans the right half, and k tracks the write position in arr. All three advance in a coordinated merge loop.

  4. Stable comparison

    if left[i] <= right[j]: arr[k] = left[i]; i += 1

    Taking from the left half when equal keeps the sort stable. Python multi-statement lines use semicolons here for compactness, though separate lines are more idiomatic.

  5. Drain remaining elements

    while i < len(left): arr[k] = left[i]; i += 1; k += 1

    After one half is exhausted, the other is already in order — copy the rest directly. At most one of the two drain loops will run.