How to recognise
the input splits into halves you can solve on their own: sort a list, build a tree from an array or from two traversals, a quad tree, a fast power, merge k sorted lists.
How to solve problems like this
- Find a split that leaves pieces of the same kind: two halves of an array, a list cut at its middle, four quadrants.
- Write the base case: the smallest piece you can answer at once, often a single item or an empty one.
- Solve each piece with a recursive call, and trust the call to return a correct answer.
- Write the combine step, and count its cost per level: O(n) per level gives O(n log n) in total.
Variant: Build a tree
The same, but to build a tree: the middle of the sorted array becomes the root and the halves become its subtrees. The halves are the same size, give or take one, so the tree comes out balanced.
- Pass index bounds (lo, hi) instead of copying sub-arrays: the split then costs O(1).
- The empty range lo > hi is the base case: it returns none.
- Pick the piece that splits the rest: the middle of a sorted array, the first value of a preorder for a tree from two traversals.
- Make the node, build the left side from one part and the right side from the other, then return the node.
Where it's used
- Sorting big data. When data does not fit in memory, PostgreSQL sorts it in pieces and then merges the sorted pieces. EXPLAIN shows this as "external merge".
- Sound and signals. The fast Fourier transform splits a signal into even and odd samples, works out each half the same way and joins the results. FFTW and numpy.fft work this way.
- Multiplying big numbers. Python multiplies very long integers with Karatsuba's method: it splits each number into two halves and gets by with three multiplications of halves instead of four.