Section 14.1

Algorithm

Definition

An algorithm is a finite, precisely stated procedure that turns an input into an output through a sequence of steps, each of which can be carried out mechanically, without judgment. An algorithm is correct when, for every input that meets its precondition (the condition the caller must guarantee before it starts), it stops after finitely many steps and its result meets its postcondition (the condition it promises at the end). An algorithm is a method and does not depend on a programming language; a program is one implementation of it.

The idea

A program must find the number 10 in a list of one million numbers sorted from smallest to largest. Comparing 10 with every number in turn may take one million comparisons. Comparing 10 with the middle number first does far better: because the list is sorted, that one comparison shows which half cannot contain 10, and repeating the step on the remaining half needs at most 20 comparisons in all. The gain comes from the method, not from the language or the machine, which is why algorithms are studied apart from the programs that implement them.

The halving method is right only if the list really is sorted, and it must also stop when 10 is absent. So an algorithm is more than its steps: it comes with a contract between the algorithm and its caller. The precondition says what the caller must provide, the postcondition says what the algorithm then promises, and a termination argument shows that the algorithm stops. A cooking recipe is a fair picture of the steps, but only up to a point: a recipe may say “season to taste”, whereas no step of an algorithm may be left to judgment.

How it works

Binary search, the halving method, shows each part of an algorithm and its contract. The input is an array §14.5 (a sequence of elements stored side by side and numbered from 0) of nn numbers, called aa, with positions 0 to n−1n - 1, and a target value xx. The precondition is that the array is sorted, a[0]≤a[1]≤…≤a[n−1]a[0] \le a[1] \le \dots \le a[n-1], and that nothing changes it while the search runs. The postcondition is that the result is a position ii with a[i]=xa[i] = x, or the answer “not found” when no position holds xx.

The search keeps a candidate range of positions, written [lo,hi)[\mathrm{lo}, \mathrm{hi}): the positions from lo\mathrm{lo} up to but not including hi\mathrm{hi}. A range that includes its lower end and excludes its upper end is called a half-open interval §14.12; it is empty exactly when lo=hi\mathrm{lo} = \mathrm{hi}. Write ⌊y⌋\lfloor y \rfloor for yy rounded down to a whole number.

  1. Set lo=0\mathrm{lo} = 0 and hi=n\mathrm{hi} = n, so that the range covers the whole array.

  2. If lo=hi\mathrm{lo} = \mathrm{hi}, the range is empty: return “not found”.

  3. Compute the middle position mid=lo+⌊(hi−lo)/2⌋\mathrm{mid} = \mathrm{lo} + \lfloor (\mathrm{hi} - \mathrm{lo})/2 \rfloor.

  4. Compare a[mid]a[\mathrm{mid}] with xx. If they are equal, return mid\mathrm{mid}. If a[mid]<xa[\mathrm{mid}] < x, set lo=mid+1\mathrm{lo} = \mathrm{mid} + 1. If a[mid]>xa[\mathrm{mid}] > x, set hi=mid\mathrm{hi} = \mathrm{mid}.

  5. Go back to step 2.

Correctness rests on a loop invariant §3.24, a statement that is true every time the search reaches step 2: if xx occurs in the array at all, it occurs at a position inside [lo,hi)[\mathrm{lo}, \mathrm{hi}). At the start the range is the whole array, so the statement holds. Sorted order keeps it true. If a[mid]<xa[\mathrm{mid}] < x, every position j≤midj \le \mathrm{mid} holds a value a[j]≤a[mid]<xa[j] \le a[\mathrm{mid}] < x, so moving lo\mathrm{lo} to mid+1\mathrm{mid} + 1 discards only positions that cannot hold xx. The case a[mid]>xa[\mathrm{mid}] > x is the mirror image. When the range becomes empty, the invariant says that xx occurs nowhere, so “not found” is the right answer.

Termination rests on the length of the range, hi−lo\mathrm{hi} - \mathrm{lo}, a whole number that is never negative. Every pass that does not return makes it smaller, because lo≤mid<hi\mathrm{lo} \le \mathrm{mid} < \mathrm{hi} and the new range leaves mid\mathrm{mid} out; a whole number that never goes below zero cannot shrink for ever. A quantity used in this way is a ranking function §3.25. In fact each pass at least halves the length, so n≥1n \ge 1 elements need at most ⌊log2n⌋+1\lfloor \log_2 n \rfloor + 1 passes, where log2n\log_2 n is the power to which 2 must be raised to give nn. For one million elements, log2n≈19.93\log_2 n \approx 19.93, so at most 19+1=2019 + 1 = 20 passes.

Worked example

Search for x=10x = 10 in the array 2,4,8,10,142, 4, 8, 10, 14, stored at positions 0 to 4, so n=5n = 5.

  1. Range [0,5)[0, 5), length 5−0=55 - 0 = 5. Middle: 0+⌊5/2⌋=0+⌊2.5⌋=20 + \lfloor 5/2 \rfloor = 0 + \lfloor 2.5 \rfloor = 2. The value a[2]=8a[2] = 8 is less than 10, so positions 0 to 2 cannot hold 10: set lo=2+1=3\mathrm{lo} = 2 + 1 = 3.

  2. Range [3,5)[3, 5), length 2. Middle: 3+⌊2/2⌋=3+1=43 + \lfloor 2/2 \rfloor = 3 + 1 = 4. The value a[4]=14a[4] = 14 is greater than 10: set hi=4\mathrm{hi} = 4.

  3. Range [3,4)[3, 4), length 1. Middle: 3+⌊1/2⌋=3+0=33 + \lfloor 1/2 \rfloor = 3 + 0 = 3. The value a[3]=10a[3] = 10 equals the target: return position 3.

The postcondition holds, because a[3]=10a[3] = 10. The range lengths were 5, 2 and 1; each is at most half of the one before, rounded down.

A search for 9 in the same array repeats the first two passes, since 9, like 10, lies between 8 and 14. In the third pass a[3]=10a[3] = 10 is greater than 9, so hi=3\mathrm{hi} = 3. The range [3,3)[3, 3) is empty, and the search returns “not found”. The answer is right: by the invariant, a 9 would have to lie in that empty range.

Now break the precondition. The array 8,2,10,4,148, 2, 10, 4, 14 is not sorted, and 4 sits at position 3. The first middle is position 2, which holds 10; 10 is greater than 4, so hi=2\mathrm{hi} = 2. The range [0,2)[0, 2) has middle 0+⌊2/2⌋=10 + \lfloor 2/2 \rfloor = 1, which holds 2; 2 is less than 4, so lo=2\mathrm{lo} = 2. The range [2,2)[2, 2) is empty, and the search answers “not found”. Every element read lay inside the array and the search stopped, yet the answer is wrong: the caller broke the precondition, and the contract then promises nothing.

Stated precisely

A Hoare triple §3.31 {P}A{Q}\{P\}\ A\ \{Q\} states: if algorithm AA starts in a state that satisfies the precondition PP, and AA stops, then the final state satisfies the postcondition QQ. This is partial correctness; it says nothing about runs that never stop. Total correctness adds termination: every run that starts in a state satisfying PP stops. C. A. R. Hoare introduced this style of reasoning in 1969.

For a loop that repeats while a condition BB holds, a loop invariant II proves partial correctness when the steps before the loop, started in a state satisfying PP, make II true; every pass started in a state satisfying both II and BB ends in a state satisfying II; and every state that satisfies II but not BB satisfies QQ. Termination needs a ranking function VV: a whole number, computed from the state, that is at least 0 whenever II and BB hold and strictly decreases on every pass. The Loop invariant and Ranking function entries treat these obligations in full.

For binary search, with jj ranging over positions:

The return from inside the loop also meets QQ, because it happens only when a[mid]=xa[\mathrm{mid}] = x. Whenever BB holds, the invariant gives 0≤lo≤mid<hi≤n0 \le \mathrm{lo} \le \mathrm{mid} < \mathrm{hi} \le n, so the element a[mid]a[\mathrm{mid}] that the search reads always exists.

Donald Knuth, in The Art of Computer Programming, lists five properties of an algorithm: finiteness, it always stops after finitely many steps; definiteness, each step is stated precisely; input, zero or more values supplied before it starts; output, one or more values with a stated relation to the input; and effectiveness, each step is basic enough to be carried out exactly and in finite time.

Limits and common mistakes

Correct means correct with respect to the stated contract, and nothing more. Binary search as given returns some position that holds xx, not necessarily the first: in the array 5,7,7,7,95, 7, 7, 7, 9, a search for 7 returns position 2 on its first comparison, although 7 also sits at position 1. A caller that needs the first position needs a different postcondition and a different algorithm.

The caller must meet the precondition; binary search does not check it, because checking that nn numbers are sorted takes n−1n - 1 comparisons, far more than the search itself. Input from an untrusted source must be checked before the call. The precondition covers the whole run: if another thread (another flow of execution sharing the same memory) changes the array during the search, the result means nothing.

A correct algorithm can still have an incorrect implementation. The textbook midpoint ⌊(lo+hi)/2⌋\lfloor (\mathrm{lo} + \mathrm{hi})/2 \rfloor equals lo+⌊(hi−lo)/2⌋\mathrm{lo} + \lfloor (\mathrm{hi} - \mathrm{lo})/2 \rfloor in mathematics, but on a machine the sum lo+hi\mathrm{lo} + \mathrm{hi} can exceed the largest value of the integer type: with 32-bit signed integers, whose largest value is 231−1=2,147,483,6472^{31} - 1 = 2{,}147{,}483{,}647, lo=1,500,000,000\mathrm{lo} = 1{,}500{,}000{,}000 and hi=2,000,000,000\mathrm{hi} = 2{,}000{,}000{,}000 give 3,500,000,0003{,}500{,}000{,}000. In C this is signed integer overflow §4.15, which is undefined behavior §4.12. Joshua Bloch described this bug, found in the binary search of the Java standard library, in 2006 [240]. The form lo+⌊(hi−lo)/2⌋\mathrm{lo} + \lfloor (\mathrm{hi} - \mathrm{lo})/2 \rfloor never exceeds hi\mathrm{hi}, so it cannot overflow.

Termination is neither automatic nor fast. A finite program text can describe a run that never ends, and no algorithm can decide, for every program and every input, whether the program stops: Alan Turing proved this in 1936 [158], and the question is called the halting problem §19.2.2. Termination must therefore be argued for each algorithm separately. And stopping is not stopping soon: a loop that counts down from 264−12^{64} - 1 to 0 stops only after about 1.8×10191.8 \times 10^{19} passes. Running time needs a separate count, the subject of asymptotic complexity §14.2.

Some programs are meant never to stop, such as an operating system, or an event loop §14.23 that waits for messages for ever. They are not algorithms in this sense; what must stop is the handling of each single request or event.

Questions answered

What are the preconditions, postconditions, and termination argument?

The preconditions are the conditions that the input and the starting state must meet before an algorithm runs; the postconditions are what the algorithm guarantees about its result and the final state when it stops; and the termination argument is a proof that it does stop for every input that meets the preconditions. Together they form the algorithm’s contract: the caller is responsible for the preconditions, and the algorithm for the postconditions and for stopping. A termination argument usually names a ranking function, a whole number computed from the state that is never negative and becomes strictly smaller on every pass through each loop.

Take binary search, which looks for a value xx in an array aa of nn elements by comparing xx with the middle element of the remaining candidates and discarding the half that cannot hold xx. Its preconditions are that aa is sorted from smallest to largest and that nothing changes aa during the search. The postcondition is that the result is a position ii with a[i]=xa[i] = x, or “not found” only when no element equals xx. The termination argument is that the number of candidate positions still to search is a whole number that is never negative and at least halves on every pass, so the search stops after at most ⌊log2n⌋+1\lfloor \log_2 n \rfloor + 1 passes, where ⌊log2n⌋\lfloor \log_2 n \rfloor is the base-2 logarithm of nn rounded down.

Related entries: Asymptotic complexity (§14.2), Loop invariant (§3.24), Ranking function (§3.25), Security versus functional correctness (§1.35), Hoare triple (§3.31), Half-open interval (§14.12). Further reading: [158, 224, 240].