Merge Sort visualization

Divide in half, sort each half recursively, then merge the two sorted halves.

Divide and conquer: split until pieces have one element, then merge sorted pieces back together by repeatedly taking the smaller front element.

Always O(n log n) and stable, at the cost of O(n) extra memory for the merge buffer.

Complexity

Time: best O(n log n), average O(n log n), worst O(n log n). Space: O(n). Difficulty: Intermediate.

Pseudocode

procedure mergeSort(A, lo, hi):
  if lo ≥ hi: return
  mid ← (lo + hi) / 2
  mergeSort(A, lo, mid); mergeSort(A, mid+1, hi)
  L ← A[lo..mid]; R ← A[mid+1..hi]
  while L and R not empty:
    take smaller of L[i], R[j] into A[k]
  copy the leftovers into A

More sorting algorithms