Video lecture
Watch on YouTube(opens in a new tab)Sub topic 1
What Is an Algorithm?
Prerequisites
This chapter assumes you can write basic programs in some language (variables, conditionals, loops, functions), read simple Python, and compute integer remainders such as 17 mod 5 = 2.
What an Algorithm Is
An algorithm is a finite sequence of precise steps that turns any valid input into the correct output. A recipe that says "add salt to taste" is a procedure. It is not an algorithm, because "to taste" is not precise.
The Properties Every Algorithm Must Have
| Property | Meaning |
|---|---|
| Finiteness | It stops after a finite number of steps on every valid input |
| Definiteness | Each step has exactly one meaning |
| Input | It takes zero or more values from a stated set |
| Output | It produces at least one result related to the input |
| Effectiveness | Each step is basic enough to do exactly, even with pencil and paper |
A common error is to ignore finiteness. A loop that works on most inputs but runs forever on one valid input does not count as an algorithm.
Problems, Algorithms and Programs
A problem states what you want, for example "find the greatest common divisor of two integers." An algorithm states how to get it, for example Euclid's method. A program is one implementation of an algorithm in a particular language. One problem can have many algorithms, and one algorithm can have many programs.
Stating the Problem Precisely
A specification has four parts:
- Inputs: the values given, with their types.
- Outputs: the values returned.
- Precondition: what must be true of the inputs before the algorithm starts.
- Postcondition: what must be true of the output when the algorithm finishes.
For GCD, the precondition is that a ≥ 0, b ≥ 0, and they are not both zero. The postcondition is that the result equals gcd(a, b).
Writing Steps in Plain Language
Number each step, use one action per step, and make every jump explicit:
Euclid's algorithm (plain language)
Input: two non-negative integers a and b, not both zero.
Output: the greatest common divisor of a and b.
1. If b is 0, the answer is a. Stop.
2. Otherwise, compute r, the remainder of a divided by b.
3. Replace a with b, and b with r.
4. Go back to step 1.Exercise
"Keep halving n until it is small." Which algorithm property does this step violate, and how would you fix it?
Show answer
It violates definiteness, because "small" has no exact meaning. A fix: "While n > 1, replace n with n div 2." This version also clearly terminates, since n strictly decreases.