Analyzing Divide and Conquer Algorithms
The loops of iterative algorithms can be analyzed by counting iterations, as we did in the first chapter. Recursive algorithms need a different tool: the execution time is expressed in terms of itself applied to smaller sizes, giving a recurrence equation. Fortunately, most divide and conquer algorithms follow one of two very regular patterns, and for both of them the solution is known in general. This lesson presents those two patterns, explains where their formulas come from, and shows how to apply them.
- How to model a divide and conquer algorithm with the parameters , and .
- The complexity formulas for division and subtraction schemes, and the intuition behind them (the recursion tree).
- How to identify , and in real code, and the most common mistakes.
- The limits of these formulas.
The Parameters , and
Both schemes are described by three parameters:
- : the number of subproblems (recursive calls) executed in each invocation;
- : how the size decreases: each subproblem has size (division) or (subtraction), where is a constant;
- : the cost of the work done in each invocation excluding the recursive calls (dividing and combining) is , a polynomial.
The base case takes constant time (or, more generally, for its small size).
Before the Formulas: a Recurrence with Numbers
A recurrence such as often looks like magic, but it is just the code described in one line. Take Mergesort: sorting elements means sorting two halves and then merging them, which goes through the elements once. If is the time to sort elements:
Nothing stops us from computing it by hand, from small to large, exactly as the computer would:
| Value | ||
|---|---|---|
| 1 | base case | 1 |
| 2 | 4 | |
| 4 | 12 | |
| 8 | 32 | |
| 16 | 80 |
Now look for the pattern, as with the loops of the first chapter. Each value is exactly : for , . The reason is the recursion tree: every level of the tree does units of merging in total (one merge of 16, two of 8, four of 4...), and there are levels. Keeping the important part, Mergesort is .
The formulas below do exactly this, once and for all, for every recurrence of the same shape. When one of them looks mysterious, go back to these three steps: write the recurrence from the code, compute a few values by hand, and look at the work per level of the tree.
Division Scheme
The execution time satisfies:
and its solution is:
This result is a particular case of the so-called master theorem.
Where does it come from? The recursion tree
Draw the tree of recursive calls. The root is the original problem, of size . It has children of size , each of which has children of size , and so on, until the base case. The tree has about levels.
| Level | Number of subproblems | Size of each one | Non-recursive work at the level |
|---|---|---|---|
| 0 | |||
| 1 | |||
| 2 | |||
| (leaves) | constant | proportional to |
The total time is the sum of all levels: multiplied by a geometric series of ratio . Everything depends on that ratio:
- (): the work decreases from each level to the next. The sum is dominated by the first term: the work at the root, . The subproblems shrink faster than they multiply.
- (): every level does the same work, , and there are levels: .
- (): the work increases from each level to the next. The sum is dominated by the last level, the leaves, whose number is . By the logarithm rule from the asymptotic notation lesson, : .
So the three cases correspond to three situations: the cost is concentrated at the top of the tree, evenly spread over all levels, or concentrated at the bottom.
ProofThe division formulaSubtraction Scheme
The execution time satisfies:
and its solution is:
(Some textbooks also list a case , but it cannot happen in practice: a recursive algorithm makes at least one call in its general case.)
The intuition is again in the recursion tree, which now has about levels:
- : a single chain of calls, with sizes . The work at each one is at most , and there are of them: . A loop of iterations whose body costs , written recursively.
- : the number of calls multiplies by at each level, through levels: calls. The algorithm is exponential, and the non-recursive work does not even matter.
An algorithm with in a subtraction scheme is exponential, and therefore unusable except for very small inputs. If you find yourself writing two or more recursive calls on (or ...), stop and think: most likely the same subproblems are being solved many times, and a different technique (an iterative version, or dynamic programming) is needed.
Identifying , and
To apply the formulas, look at the code of the recursive method and answer three questions:
- How many recursive calls are executed in one invocation (in the general case)? That is . Count the calls that are actually executed, not the ones that are written: in binary search there are two calls in the code, but only one of them runs in each invocation, so . And a call inside a loop that runs times counts times.
- What is the size of each recursive call? If it is , the scheme is division; if it is , subtraction.
- What is the cost of everything else (loops, copies, partitions, merges)? If it is , that gives . A constant amount of work means .
For example, in Mergesort:
public void mergesort(int[] v, int left, int right) {
if (left < right) { // base case: one element, constant time
int center = (left + right) / 2; // O(1)
mergesort(v, left, center); // call 1, on half the elements
mergesort(v, center + 1, right); // call 2, on the other half
merge(v, left, center, right); // O(n): goes through the n elements once
}
}
Two calls are executed (), each one on half of the elements (, division), and the rest of the work is dominated by the linear merge (). Since , Mergesort is .
Examples
- Division
- Subtraction
| Algorithm | Case | Complexity | |||
|---|---|---|---|---|---|
| Binary search | 1 | 2 | 0 | () | |
| Sum of a vector by division | 2 | 2 | 0 | () | |
| Mergesort | 2 | 2 | 1 | () | |
| Quicksort (balanced partitions) | 2 | 2 | 1 | ||
| Tennis tournament | 2 | 2 | 2 | () | |
| Multiplication of large integers (4 products) | 4 | 2 | 1 | () | |
| Karatsuba multiplication (3 products) | 3 | 2 | 1 | () |
| Algorithm | Case | Complexity | |||
|---|---|---|---|---|---|
| Factorial | 1 | 1 | 0 | ||
| Sum of a vector by subtraction | 1 | 1 | 0 | ||
| Sequential search, recursive | 1 | 1 | 0 | ||
| Quicksort (most unbalanced partitions) | 1 | 1 | 1 | ||
| Towers of Hanoi | 2 | 1 | 0 | ||
| Naive Fibonacci, (upper bound, see below) | 2 | 1 | 0 |
The naive Fibonacci does not fit the scheme exactly, because its two calls have different sizes, and . Replacing by can only make the tree larger, so the scheme with , gives an upper bound, . The exact growth is about , still exponential.
Notice how Quicksort appears in both tables: with perfectly balanced partitions, it follows a division scheme (, , ); with the most unbalanced ones, a subtraction scheme in which one of the two parts is empty, so only one non-trivial call remains (, , ). Both formulas confirm what we found in the sorting chapter: in the best case and in the worst.
🧠 Checkpoint: Analyze these schemes
Question: Give the complexity of (1) an algorithm that splits a problem of size into 8 subproblems of size and combines them in , and (2) the same with 7 subproblems.
Answer: (1) , , : , so . This is the divide and conquer multiplication of matrices with 8 products of half-size blocks: no better than the classic algorithm. (2) With : . This is Strassen's algorithm (Strassen, 1969), which saves one block multiplication at the cost of more additions, and beats the classic cubic algorithm for large matrices. The same trick, saving one recursive call, makes Karatsuba's multiplication faster.
How Each Parameter Affects the Cost
The formulas give useful design guidance:
- Reducing (fewer subproblems) is often the key to a faster algorithm when : Karatsuba (4 to 3 products) and Strassen (8 to 7) are famous examples.
- Reducing (cheaper division and combination) helps when . For example, Mergesort with an merge would be instead of .
- Division beats subtraction: dividing the size by 2 instead of subtracting 1 turns levels into , and can turn an exponential algorithm into a polynomial one.
Limits of the Formulas
These formulas cover the most common cases, but not all of them:
- Subproblems of different sizes. If an algorithm divides into parts of sizes and , or into parts whose size depends on the data (Quicksort with random pivots, Quickselect), the formulas do not apply directly. The recursion tree, or probabilistic analysis, is needed. For example, Quicksort's average case is , and Quickselect's average case is , although neither follows exactly any of the two schemes.
- Non-polynomial non-recursive work. If dividing and combining costs, for example, , is not an integer power. The recurrence has solution , which the simple formulas do not give. The general master theorem covers many of these cases.
- Exact constants. The formulas give the order of growth, not the exact time.
When an algorithm does not fit the schemes, the safest method is to draw the recursion tree, compute the work at each level and add it up, as we did above.
Predicting Execution Times
Once the complexity is known, the techniques of the first chapter apply directly. For example, if Mergesort () takes 2 seconds for , for it will take about
And if the Towers of Hanoi () take 1 second for 20 discs, then 30 discs will take about seconds (17 minutes), and 64 discs, about seconds: more than 500,000 years.
- Counting the recursive calls written instead of those executed. Binary search writes two calls but executes one: .
- Taking from the recursive calls. is the cost of the non-recursive work (dividing and combining), .
- Applying the division formulas to a subtraction scheme. First decide whether the size is divided () or reduced ().
Summary
- Divide and conquer algorithms are analyzed with recurrences, characterised by (number of subproblems), (how the size decreases) and (cost of dividing and combining, ).
- Division (): if ; if ; if .
- Subtraction (): if ; , exponential, if .
- The recursion tree explains the formulas: the cost is concentrated at the top, evenly spread, or concentrated at the leaves.
- Count the recursive calls that are executed, not the ones written. Subproblems of unequal or data-dependent size need a specific analysis.
Practice
- 🌳 Draw the tree. Draw the recursion tree of for , write the work at each level, and check that the total grows like .
- 🔍 Identify the parameters. Write a recursive method that searches for the maximum of a vector by dividing it into three parts. What are , and ? What is its complexity?
- ⚖️ Compare designs. Problem A is solved by dividing into 2 halves and combining in ; problem B by dividing into 4 quarters and combining in . Which algorithm has the better complexity?
- 💻 Measure. In lab session 3 you will measure recursive models of each type. Before measuring, predict how the time should grow when doubles (division) or when increases by a constant (subtraction with ), and then compare with your measurements.
Errors, suggestions and public questions open a form on GitHub, visible to everyone.