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.

Exactly the same pattern recurs on each half, down to the smallest size.
The stageWhat happens in it
DivideTwo smaller problems of the same kind
ConquerSolving each, usually recursively
JoinBuilding 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 # join

Why 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

  1. Each half returns its largest.
  2. The joining is one comparison.
  3. It does not depend on the list’s size.
  4. So the whole algorithm is cheap.

Example 2 — why a halving search is cheaper still

  1. It divides in two as usual.
  2. But solves only one half.
  3. And then there is nothing to join at all.
  4. Knowing the list is sorted makes that possible.
At every level the joining is one comparison, whatever the size — so the whole algorithm is cheap.