← again tap: answer good → ↑ swipe up at the end: next
Question
What are the three steps of divide-and-conquer, and where does the recursion stop?
Answer
Divide the input into disjoint parts, recur by solving each part with the same algorithm, then conquer by combining the partial solutions into the solution for the whole. The recursion stops at subproblems of size 0 or 1, which need no work at all.
Divide-and-conquer is a design pattern, not one particular algorithm. For sorting a sequence $S$ it reads:
- Divide: split $S$ into (usually two) disjoint parts $S_1$ and $S_2$.
- Recur: sort $S_1$ and $S_2$ by calling the same algorithm on each part.
- Conquer: combine the two sorted parts into the sorted $S$.
The recursion needs a floor, the base case: a sequence with 0 or 1 elements is already sorted, so the call returns it unchanged. Every other call hands strictly smaller problems to its recursive calls, so the recursion is guaranteed to reach that floor. Insertion-sort starts from the same fact: its sorted part begins as the first element alone, because a single element is always sorted.
The pattern leaves open where the real work happens, and the two classic sorts answer that in opposite ways: merge-sort splits blindly in the middle and does its comparisons when combining, quick-sort does its comparisons when splitting and combines by simply writing the parts one after the other.
Go deeper:
Divide-and-conquer algorithm — the paradigm with its classic examples, from binary search to fast multiplication.
Question
How does merge-sort sort a sequence of $n$ elements?
Answer
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:
Merge sort — top-down and bottom-up versions, analysis, and variants for linked lists and external storage.
VisuAlgo: sorting — run merge-sort and quick-sort step by step on your own input.