LOGBOOK

HELP

Quiz Entry - updated: 2026.11.26

How does merge-sort sort a sequence of $n$ elements?

Cut the sequence into two halves of about $n/2$ elements, sort each half recursively with merge-sort, then merge the two sorted halves into one sorted sequence. Sequences of 0 or 1 elements are returned as they are.

Algorithm mergeSort(S, C)          // C: comparator that defines the order
  if S.size() > 1
    (S1, S2) ← partition(S, n/2)   // first n/2 elements, and the rest
    S1 ← mergeSort(S1, C)
    S2 ← mergeSort(S2, C)
    S  ← merge(S1, S2)
  return S

The three divide-and-conquer steps map one to one: partition is the divide, the two recursive calls are the recur, and merge is the conquer. The partition here only cuts the sequence at position $n/2$, without looking at a single value; it has nothing to do with quick-sort's partition step, despite the name. All comparisons happen inside merge. That is why merge-sort hardly cares about the input order: the cuts are always in the middle, whatever the values are.

The comparator $C$ makes the algorithm generic: the same code sorts numbers, strings or records, ascending or descending, depending on which comparison is passed in.

Go deeper:

  • doc Merge sort — top-down and bottom-up versions, analysis, and variants for linked lists and external storage.
  • tool VisuAlgo: sorting — run merge-sort and quick-sort step by step on your own input.

From Quiz: ADS / Merge-Sort and Quick-Sort | Updated: Nov 26, 2026