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 numbers, called , with positions 0 to , and a target value . The precondition is that the array is sorted, , and that nothing changes it while the search runs. The postcondition is that the result is a position with , or the answer “not found” when no position holds .
The search keeps a candidate range of positions, written : the positions from up to but not including . 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 . Write for rounded down to a whole number.
Set and , so that the range covers the whole array.
If , the range is empty: return “not found”.
Compute the middle position .
Compare with . If they are equal, return . If , set . If , set .
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 occurs in the array at all, it occurs at a position inside . At the start the range is the whole array, so the statement holds. Sorted order keeps it true. If , every position holds a value , so moving to discards only positions that cannot hold . The case is the mirror image. When the range becomes empty, the invariant says that occurs nowhere, so “not found” is the right answer.
Termination rests on the length of the range, , a whole number that is never negative. Every pass that does not return makes it smaller, because and the new range leaves 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 elements need at most passes, where is the power to which 2 must be raised to give . For one million elements, , so at most passes.
Worked example
Search for in the array , stored at positions 0 to 4, so .
Range , length . Middle: . The value is less than 10, so positions 0 to 2 cannot hold 10: set .
Range , length 2. Middle: . The value is greater than 10: set .
Range , length 1. Middle: . The value equals the target: return position 3.
The postcondition holds, because . 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 is greater than 9, so . The range 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 is not sorted, and 4 sits at position 3. The first middle is position 2, which holds 10; 10 is greater than 4, so . The range has middle , which holds 2; 2 is less than 4, so . The range 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 states: if algorithm starts in a state that satisfies the precondition , and stops, then the final state satisfies the postcondition . This is partial correctness; it says nothing about runs that never stop. Total correctness adds termination: every run that starts in a state satisfying stops. C. A. R. Hoare introduced this style of reasoning in 1969.
For a loop that repeats while a condition holds, a loop invariant proves partial correctness when the steps before the loop, started in a state satisfying , make true; every pass started in a state satisfying both and ends in a state satisfying ; and every state that satisfies but not satisfies . Termination needs a ranking function : a whole number, computed from the state, that is at least 0 whenever and hold and strictly decreases on every pass. The Loop invariant and Ranking function entries treat these obligations in full.
For binary search, with ranging over positions:
: ; ; and nothing changes during the search.
: either the result is a position with and , or the result is “not found” and for every with .
: .
: , and for every with or .
.
The return from inside the loop also meets , because it happens only when . Whenever holds, the invariant gives , so the element 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 , not necessarily the first: in the array , 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 numbers are sorted takes 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 equals in mathematics, but on a machine the sum can exceed the largest value of the integer type: with 32-bit signed integers, whose largest value is , and give . 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 never exceeds , 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 to 0 stops only after about 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 in an array of elements by comparing with the middle element of the remaining candidates and discarding the half that cannot hold . Its preconditions are that is sorted from smallest to largest and that nothing changes during the search. The postcondition is that the result is a position with , or “not found” only when no element equals . 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 passes, where is the base-2 logarithm of 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].