Divide and conquer example: Mergesort [00PL]
- October 19, 2026
The material in this section is presented via a POGIL activity.
A classic example of a divide-and-conquer algorithm is mergesort, which works by splitting the input list into two halves, recursively sorting each half, and then merging the sorted halves together.
Algorithm Mergesort [00PP]
- October 19, 2026
\mathsf {mergesort}(xs) =
\mathsf {if} |\mathit {xs}| \leq 1:
\mathsf {return} \mathit {xs}
split \mathit {xs} into halves (\mathit {xs}_1, \mathit {xs}_2)
\mathit {xs}_1' \gets \mathsf {mergesort}(\mathit {xs}_1)
\mathit {xs}_2' \gets \mathsf {mergesort}(\mathit {xs}_2)
\mathit {xs}' \gets \mathsf {merge}(\mathit {xs}_1, \mathit {xs}_2)
\mathsf {return} \mathit {xs}'
Mergesort analysis [00PQ]
- October 19, 2026
How long does mergesort take on a list of length n? Looking at the code above, we can see that
- It takes \Theta (1) in the base case (a list of length \leq 1).
- Otherwise, it makes two recursive calls to itself on lists of length approximately n/2.
- After the recursive calls complete, it does \Theta (n) additional work to merge the two sorted lists into a single sorted list.
If we draw out a tree showing all the recursive calls of \mathsf {mergesort} on an initial input of length n, it looks something like this:
The expression at each node indicates both the size of the input to that recursive call, as well as the amount of work which happens at that node (since the amount of work at each node is linear). We can see that- The tree has height \lg n, since we divide the input in half at each level until reaching a base case of 1.
- There is n total work happening at each level: n = n/2 + n/2 = n/4 + n/4 + n/4 + n/4 = \dots .