Divide and Conquer: Classic Problems
This lesson presents some of the most famous divide and conquer algorithms. Two of them, Mergesort and Quicksort, we already know from the sorting chapter; now we can analyze them with the formulas of this chapter. The others (the Towers of Hanoi, the multiplication of large integers, the tennis tournament and the Tromino puzzle) show how the paradigm solves problems that would be hard to approach in any other way.
- How Mergesort and Quicksort fit the division and subtraction schemes.
- The recursive solution of the Towers of Hanoi, and why it cannot be faster than exponential.
- How Karatsuba's algorithm multiplies large integers faster than the classic method by saving one multiplication.
- Two constructive problems solved by divide and conquer: scheduling a tennis tournament and tiling a board with trominoes.
Mergesort
Mergesort sorts a vector by dividing it into two halves, sorting each half recursively and merging the two sorted halves:
void mergesort(int left, int right, int[] elements) {
if (right > left) {
int center = (right + left) / 2; // index of the middle element
mergesort(left, center, elements); // sort the left half
mergesort(center + 1, right, elements); // sort the right half
combine(left, center, center + 1, right, elements); // merge both halves
}
}
To combine two sorted halves, copy them into two auxiliary arrays, then repeatedly take the smaller of the first remaining elements of both and put it back into the original array; when one of them runs out, copy the rest of the other one:
void combine(int x1, int x2, int y1, int y2, int[] elements) {
int sizeX = x2 - x1 + 1, sizeY = y2 - y1 + 1;
int[] x = new int[sizeX], y = new int[sizeY];
for (int i = 0; i < sizeX; i++) x[i] = elements[x1 + i]; // copy the left half
for (int i = 0; i < sizeY; i++) y[i] = elements[y1 + i]; // copy the right half
int i = 0, j = 0, k = x1;
while (i < sizeX && j < sizeY) // take the smaller each time
elements[k++] = (x[i] <= y[j]) ? x[i++] : y[j++];
while (i < sizeX) elements[k++] = x[i++]; // copy the rest
while (j < sizeY) elements[k++] = y[j++];
}
With 4 5 6 1 3 2 7 8:
Analysis. Divide and conquer by division: subproblems, (each of size ), (merging costs ). Since (): , in all cases, because the division is always into halves, whatever the data.
Taking x[i] when x[i] <= y[j] (that is, preferring the left half in case of a tie) makes Mergesort stable. Its weakness is the extra memory for the auxiliary arrays: .
Quicksort, Revisited
Quicksort chooses a pivot, partitions the vector in and sorts both parts recursively. The two extreme cases fit our two schemes:
- Balanced partitions (the pivot is the median): division scheme with , , . Since : .
- Completely unbalanced partitions (the pivot is the smallest or largest element): one part is empty, so there is effectively one subproblem of size : subtraction scheme with , , . Since : .
The average case lies between both and, as we saw in the sorting chapter, is . Unlike Mergesort, all the work of Quicksort is done when dividing (partitioning); combining requires nothing.
The Towers of Hanoi
There are three vertical rods and discs of different sizes, initially stacked on the first rod (the source) from largest at the bottom to smallest at the top. The goal is to move the whole stack to the last rod (the target), using the middle rod as an auxiliary (work) rod, with two rules:
- only one disc can be moved at a time;
- a disc can never be placed on top of a smaller one.
The puzzle was invented by the French mathematician Édouard Lucas in 1883, together with a legend: in a temple, monks are moving a tower of 64 golden discs, and when they finish, the world will end.
The recursive strategy
The problem seems complicated, but divide and conquer makes it simple. To move discs from the source to the target:
- Move the top discs from the source to the work rod (using the target as auxiliary).
- Move the largest disc, now alone, from the source to the target.
- Move the discs from the work rod to the target (using the source as auxiliary).
Steps 1 and 3 are the same problem with one disc fewer, so they are solved recursively. The base case is a single disc, which is moved directly.
/** Moves nDiscs from the source rod to the target rod, with the aid of the work rod */
void move(int nDiscs, char source, char work, char target) {
if (nDiscs == 1) {
moveDisc(source, target); // a single disc: move it directly
} else {
move(nDiscs - 1, source, target, work); // 1. n-1 discs to the work rod
moveDisc(source, target); // 2. the largest disc to the target
move(nDiscs - 1, work, source, target); // 3. n-1 discs on top of it
}
}
With 3 discs on rod A (source), B (work) and C (target), the call move(3, 'A', 'B', 'C') produces 7 moves:
| Move | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| From → to | A → C | A → B | C → B | A → C | B → A | B → C | A → C |
Moves 1 to 3 transfer the two smallest discs to B; move 4 carries the largest disc to C; moves 5 to 7 transfer the two small discs on top of it.
Analysis
Divide and conquer by subtraction: (two recursive calls), (each one with discs), (moving one disc is constant). Since : . More precisely, the number of moves satisfies with , so .
The complexity is not polynomial, but here this is not a flaw of the algorithm: it can be proved that no solution can use fewer than moves (the largest disc must move at least once, and before it does, all the others must be out of the way, twice). The problem itself is exponential. With 64 discs, moves: at one move per second, about 585,000 million years. The world is safe.
🧠 Checkpoint: How long does Hanoi take?
Question: How many moves are needed with 10 discs? And with 30 discs, at one move per second?
Answer: With 10 discs, 1,023 moves. With 30 discs, seconds: about 34 years. Every extra disc doubles the time.
Multiplication of Large Integers
Computers multiply numbers of fixed size (such as long) in a single instruction. But cryptography, computer algebra or the calculation of the digits of need to multiply integers with thousands or millions of digits, which must be stored as arrays of digits. How fast can we multiply two numbers of digits?
The classic algorithm
The method we learnt at school multiplies each digit of one number by each digit of the other, and adds the shifted partial products:
981
× 1234
------
3924
2943
1962
981
-------
1210554
It performs one-digit multiplications: .
A first divide and conquer attempt
Assume, to simplify, that both numbers have digits, with a power of 2. Split each number into two halves of digits:
Then:
This requires 4 multiplications of numbers of digits (, , and ), which are computed recursively, plus some additions and shifts (multiplying by a power of 10 is just a shift), which are . The base case is the multiplication of two one-digit numbers.
Analysis: , , . Since (): . No improvement at all over the classic algorithm!
Karatsuba's algorithm
In 1960, Anatoly Karatsuba (then a student) discovered how to save one multiplication. The key observation is:
Since and are needed anyway, the middle term costs only one extra multiplication, , instead of two:
LargeInteger multiply(LargeInteger u, LargeInteger v) { // n digits each
if (n == 1) return u * v; // one-digit product
LargeInteger w = firstHalf(u), x = secondHalf(u);
LargeInteger y = firstHalf(v), z = secondHalf(v);
LargeInteger p = multiply(w, y); // w·y
LargeInteger q = multiply(x, z); // x·z
LargeInteger r = multiply(w.add(x), y.add(z)); // (w+x)·(y+z)
return p.shift(n).add(r.subtract(p).subtract(q).shift(n / 2)).add(q);
}
Analysis: , , . Since (): . Saving a single multiplication in each call changes the exponent, which makes a huge difference for large numbers: for numbers of a million digits, while . We implemented this algorithm on binary numbers and checked it against Java's BigInteger on 200 random pairs of 2,000-bit numbers.
🧠 Checkpoint: Karatsuba versus the classic method
Question: Multiplying two numbers of 1,024 digits, and recursing down to single digits, how many single-digit products does Karatsuba's algorithm compute? And the classic method?
Answer: Karatsuba halves the size 10 times () and makes 3 products at each level: 59,049 single-digit products. The classic method makes 1,048,576, about 18 times more.
What does Java use?
Java's BigInteger combines several algorithms depending on the size of the operands: the classic method for small numbers (where its low overhead wins), Karatsuba () for larger numbers and Toom-Cook (, a generalization that splits into three parts) for the largest ones. Even faster algorithms, based on the fast Fourier transform, exist for gigantic numbers.
The Tennis Tournament
We must organize a tennis tournament with players. Each player must play exactly once against each of the other players, and one match per day. The goal is to build the calendar of the tournament in days (when is even, everyone plays every day; when is odd, each player has one day off).
To simplify, consider first . The solution can be represented as a table of rows and columns, where the element is the player that faces player on day .
The strategy
- Base case (): a single match on day 1.
- Recursive case (, ): split the players into two halves, and , and recursively build the calendar of each half, which covers the first days. It remains to schedule the matches between both halves on the remaining days:
- the first player of the first half plays, on successive days, against the players of the second half in increasing order;
- each following player of the first half uses the same sequence with a cyclic shift of one position;
- the players of the second half are filled in symmetrically (if plays on a day, then plays on that day).
void schedule(int[][] table, int lower, int upper) {
if (upper - lower == 1) { // base case: two players
table[lower][1] = upper;
table[upper][1] = lower;
} else {
int center = (lower + upper) / 2;
schedule(table, lower, center); // calendar of the first half
schedule(table, center + 1, upper); // calendar of the second half
completeCrossMatches(table, lower, center, upper); // O(n²): the remaining n/2 days
}
}
For , the resulting calendar (each row lists the opponents of a player, day by day) is:
| Player | Day 1 | Day 2 | Day 3 | Day 4 | Day 5 | Day 6 | Day 7 |
|---|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 2 | 1 | 4 | 3 | 6 | 7 | 8 | 5 |
| 3 | 4 | 1 | 2 | 7 | 8 | 5 | 6 |
| 4 | 3 | 2 | 1 | 8 | 5 | 6 | 7 |
| 5 | 6 | 7 | 8 | 1 | 4 | 3 | 2 |
| 6 | 5 | 8 | 7 | 2 | 1 | 4 | 3 |
| 7 | 8 | 5 | 6 | 3 | 2 | 1 | 4 |
| 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
Days 1 to 3 contain the two calendars of 4 players (1-4 and 5-8), built recursively; days 4 to 7 contain the cross matches, with the cyclic shifts clearly visible. We checked the table: every player faces every other player exactly once, and the matches of each day are consistent.
Analysis. Divide and conquer by division: , , and completing the cross matches fills cells for each half: . Since (): . This is optimal, since the table itself has cells to fill.
Other values of . If is odd, add a fictitious player: the problem becomes one with an even number of players, and the day on which a player "plays" against the fictitious one is his day off. If is even but not a power of 2, the problem can be solved by combining the solutions for players (adding a fictitious player when is odd) with a slightly different completion step.
The Tromino Puzzle
A tromino is an L-shaped figure formed by three squares. We have a board of cells, with a power of 2, in which one cell is missing (or blocked). The goal is to cover all the other cells with trominoes, without overlaps. Is it always possible, wherever the missing cell is? Divide and conquer answers yes, and gives the construction at the same time:
- Base case (): a board with one missing cell is exactly one tromino.
- Recursive case: divide the board into four quadrants of . The missing cell is in one of them. Place one tromino at the center of the board, covering the corner cell of each of the other three quadrants that touches the center. Now each of the four quadrants has exactly one cell that is missing or covered, so each one is a smaller instance of the same problem, and can be tiled recursively.
The number of cells to cover is , which is always divisible by 3 when is a power of 2, and the algorithm uses exactly trominoes.
Analysis. With as the side of the board: subproblems, , and placing the central tromino is constant, . Since : , proportional to the number of cells, which is optimal. You can try the puzzle interactively at the Tromino puzzle page by Norton Starr.
The Tromino puzzle is also a beautiful example of a proof by induction: the recursive algorithm is, at the same time, a proof that the tiling always exists.
- Expecting four half-size products to beat the classic multiplication. With , , it is still ; Karatsuba needs only three.
- Forgetting the auxiliary array of Mergesort. It is not in place: it needs extra memory.
- Looking for a polynomial algorithm for the Towers of Hanoi. moves are necessary: the problem itself is exponential.
Summary
| Problem | Scheme | Complexity | |||
|---|---|---|---|---|---|
| Mergesort | Division | 2 | 2 | 1 | |
| Quicksort, best case | Division | 2 | 2 | 1 | |
| Quicksort, worst case | Subtraction | 1 | 1 | 1 | |
| Towers of Hanoi | Subtraction | 2 | 1 | 0 | |
| Large integers, 4 products | Division | 4 | 2 | 1 | |
| Karatsuba | Division | 3 | 2 | 1 | |
| Tennis tournament | Division | 2 | 2 | 2 | |
| Tromino ( = side) | Division | 4 | 2 | 0 |
Practice
- ✍️ Trace Mergesort. Sort 5 6 1 3 9 8 7 4 2 with Mergesort, drawing the tree of divisions and the result of each merge.
- 🗼 Hanoi. Write the sequence of moves for 4 discs. Then write a program that prints the moves and measures the time for Does the time double with each additional disc?
- ✖️ Karatsuba by hand. Multiply with Karatsuba's method, writing the three products of the first level.
- 🎾 The calendar. Build the calendar for players by hand with the strategy of this lesson. Then implement
completeCrossMatchesand check your table for against the one above. - 🧩 Trominoes. Tile by hand an board with the missing cell at row 2, column 6. How many trominoes do you need?
Errors, suggestions and public questions open a form on GitHub, visible to everyone.