Grade 9 Computer Science · Divide and conquer
The three stages
Halve, solve each half, and join — and why the joining is the interesting part.
One line that reveals what an algorithm costs
Two algorithms cut the problem in two in exactly the same way, and one of them is far faster than the other. The difference is not in the division and not in the recursion, but in a stage most people skip when reading code — and a halving search simply does without it.
Last year we saw the halving search and took it as a trick. Now what stands behind it can be said — a general pattern recurring in many places, and probably the most important algorithmic idea you will meet.
| The stage | What happens in it |
|---|---|
| Divide | Two smaller problems of the same kind |
| Conquer | Solving each, usually recursively |
| Join | Building the answer from the two answers |
def largest(items):
if len(items) == 1:
return items[0] # base
mid = len(items) // 2
left = largest(items[:mid]) # conquer
right = largest(items[mid:])
return left if left > right else right # joinWhy the halving search is a special case
In the halving search something happens worth noticing: it divides in two, but does not solve both halves — it knows in advance the answer can be in only one of them, and so gives up the other entirely. And when only one half is solved, the joining becomes unnecessary too: the half’s answer is the answer. That makes it the cheapest case in the pattern, and it explains why it is so fast. The rule that follows: the more can be given up, the cheaper the algorithm — and the way to give up is to know something in advance, such as the list being sorted.
Example 1 — a cheap joining
- Each half returns its largest.
- The joining is one comparison.
- It does not depend on the list’s size.
- So the whole algorithm is cheap.
Example 2 — why a halving search is cheaper still
- It divides in two as usual.
- But solves only one half.
- And then there is nothing to join at all.
- Knowing the list is sorted makes that possible.