Skip to content

Visualizers

Merge Sort Visualizer

Step-through animation of Merge Sort showing recursive divide-and-conquer.

native (Canvas API) Client-side
Ready to visualize

Execution Log

Dividing Steps: 0
Merging Steps: 0
Current Action:

Idle

Legend:

Unsorted / Inactive
Currently Merging
Active Subdivision
Sorted Subarray

Merge Sort Algorithm

Merge Sort is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, meaning it maintains the relative order of equal elements.

How It Works

  1. Divide the unsorted list into $n$ sublists, each containing one element (a sublist of one element is considered sorted).
  2. Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining. This will be the sorted list.

Implementation

function mergeSort(arr, l = 0, r = arr.length - 1) {
  if (l >= r) return arr;
  const m = Math.floor((l + r) / 2);
  mergeSort(arr, l, m);
  mergeSort(arr, m + 1, r);
  merge(arr, l, m, r);
  return arr;
}

function merge(arr, l, m, r) {
  const left = arr.slice(l, m + 1);
  const right = arr.slice(m + 1, r + 1);
  let i = 0, j = 0, k = l;
  
  while (i < left.length && j < right.length) {
    if (left[i] <= right[j]) {
      arr[k++] = left[i++];
    } else {
      arr[k++] = right[j++];
    }
  }
  while (i < left.length) arr[k++] = left[i++];
  while (j < right.length) arr[k++] = right[j++];
}