Video lecture
Watch on YouTube(opens in a new tab)Sub topic 1
What Is an Algorithm?
An algorithm is a finite, precise sequence of steps that solves every instance of a well-defined problem. You have been writing algorithms every time you wrote a loop that sorted, searched, or summed something. Usually the algorithm stayed hidden inside the code. This tutorial pulls it out and looks at it directly. This chapter sets up the working idea that every later chapter refines.
Prerequisites
This chapter assumes you have:
- Basic programming experience in any language, including variables, conditionals, loops and functions.
- Comfort with integer arithmetic, especially the remainder operation (
a % bin Python,a mod bin maths). - The ability to read short Python functions and predict what they print.
You do not need any background in discrete mathematics or formal proof. Later chapters introduce the reasoning tools as they come up.
A Working Definition
Here is the definition this tutorial uses:
An algorithm is a finite list of unambiguous instructions that, given any valid input from a stated set, can be carried out mechanically and always produces the correct output after a finite number of steps.
Each part of that sentence does a job:
| Phrase | What it rules out |
|---|---|
| finite list of instructions | An endless description that can never be written down |
| unambiguous | Steps like "adjust as needed" that two people would carry out differently |
| any valid input from a stated set | A method that only works for one example |
| carried out mechanically | Steps that need insight, taste or guessing |
| correct output | A procedure that runs but answers the wrong question |
| finite number of steps | A procedure that may run forever on some input |
The next chapter turns these phrases into the classic list of properties: finiteness, definiteness, input, output and effectiveness. For now, use the definition as a test you can apply to any procedure.
The Running Example: Euclid's Algorithm
Euclid described a method for the greatest common divisor (GCD) around 300 BCE, and it is still in use. The GCD of two integers is the largest integer that divides both of them exactly. For example, gcd(48, 18) = 6.
Here is the method in numbered plain language:
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.Check it against the definition:
- The list has four steps, so it is finite.
- Each step says exactly what to do. "Compute the remainder" has one meaning for integers.
- It covers every pair of non-negative integers that are not both zero, not just one pair.
- A person with pencil and paper, or a machine, can follow it without understanding why it works.
- It stops, because b gets strictly smaller each time round and cannot drop below zero. Chapter 11 makes this argument carefully.
Here is the same algorithm as a Python program. This version prints each state so you can watch the steps happen:
def gcd(a, b):
while b != 0:
print(f"a={a}, b={b}")
a, b = b, a % b
print(f"a={a}, b={b} -> stop")
return a
print(gcd(48, 18))Running it prints:
a=48, b=18
a=18, b=12
a=12, b=6
a=6, b=0 -> stop
6The algorithm needed three remainder operations to reach the answer. Notice that the plain-language version and the Python version describe the same algorithm. Chapter 3 explains why that distinction matters.
The Shape of Every Algorithm
Every algorithm has the same outer shape. An input comes in, a finite sequence of mechanical steps transforms it, and an output comes out. The steps may repeat, but they must eventually reach a stopping point.
The loop in the diagram is where the work happens. The decision box is what lets the loop end. An algorithm without a reachable exit is not an algorithm, however good its steps look.
What Is Not an Algorithm
The definition is easier to understand once you see things that fail it.
A cooking recipe that says "season to taste." This step is not definite. Two cooks will do different things, and neither can check their result against a stated output.
"Try numbers until you find one that divides both a and b, starting from the larger one." This is close to an algorithm, but it is underspecified. Try them in what order? Stop when? Once you write "count down from min(a, b) to 1 and return the first number that divides both," it becomes a valid algorithm. It is just slower than Euclid's.
A procedure that only handles the example. "Divide 48 by 18, then 18 by 12, then 12 by 6, and the answer is 6" is a worked calculation for one instance, not a method for the problem.
A program that loops forever on some valid input. Consider this:
def bad_gcd(a, b):
while b != 0:
a, b = b, a - b
return abad_gcd(6, 4) gives states (6, 4), (4, 2), (2, 2), (2, 0) and returns 2, which is correct. However, bad_gcd(4, 6) gives (4, 6), (6, -2), (-2, 8), (8, -10), and so on. The values grow without limit and the loop never ends. Correct output on some inputs does not make a procedure an algorithm for the whole problem.
Algorithms Versus Heuristics and Processes
Two neighbouring ideas cause confusion.
A heuristic is a rule of thumb that usually gives a good answer but is not guaranteed to give the correct one. "To pack a suitcase, put the biggest items in first" is a heuristic. It can be written as precise steps, but it does not guarantee the best packing. Computer scientists still call precise heuristic procedures "algorithms" (for example, "greedy algorithm"), but then the problem has to be stated honestly as "find a reasonably good packing," not "find the best packing." The algorithm is correct only relative to the problem as stated. Chapter 4 covers how to state problems precisely.
A process that is meant to run indefinitely, such as a web server or an operating system scheduler, does not terminate. People still describe its inner pieces with algorithms, such as how to handle one request. The never-ending outer loop is a different kind of object. In this tutorial, "algorithm" always means a procedure that terminates.
Why the Idea Matters
Separating the algorithm from any particular piece of code gives you three things:
- Portability of ideas. Euclid's method works the same in Python, C, a spreadsheet, or by hand. Once you understand it, you can implement it anywhere.
- Reasoning before running. You can argue that a method is correct and that it stops before you write a line of code. That catches bugs that testing on a few inputs would miss, as
bad_gcdshowed. - Comparing methods. Euclid's algorithm and the count-down method solve the same problem. Only by treating them as algorithms can you ask which one does less work. Chapter 14 answers that question with step counts and Big-O notation.
Where the Word Comes From
The word "algorithm" comes from the name of Muhammad ibn Musa al-Khwarizmi, a ninth-century Persian mathematician. His books explained step-by-step methods for arithmetic with Hindu-Arabic numerals. Latin translations rendered his name as "Algoritmi," and the term came to mean any systematic calculating procedure. In the 1930s, Alan Turing and Alonzo Church gave formal definitions of "mechanically computable." The informal definition in this chapter matches those formal models for every practical purpose.
Summary of the Working Model
- An algorithm solves a whole class of inputs, not one example.
- Every step must be precise enough to carry out without judgement.
- It must always stop and always give the correct output for valid input.
- The same algorithm can be written in plain language, pseudocode, a diagram, or code.
Exercise
Is the following an algorithm for finding the GCD of two positive integers a and b? "Let m be the smaller of a and b. For d = m, m-1, ..., 1: if d divides both a and b, output d and stop." Justify your answer against the working definition.
Show answer
Yes. It is a finite list of steps, each step (comparing, taking a remainder to test divisibility) is unambiguous and mechanical, and it works for every pair of positive integers. It always stops because d = 1 divides every integer, so the loop runs at most m times. The first d it finds is the largest common divisor, because it counts down from the largest possible candidate. It is correct but usually much slower than Euclid's algorithm.
Exercise
Trace badgcd(3, 5) for four iterations and explain why it fails the definition of an algorithm for GCD, even though badgcd(5, 3) returns the correct answer.
Show answer
States: (3, 5) -> (5, -2) -> (-2, 7) -> (7, -9) -> (-9, 16). The values alternate in sign and grow in size, so b never becomes 0 and the loop never ends. bad_gcd(5, 3) gives (5, 3), (3, 2), (2, 1), (1, 1), (1, 0) and returns 1, which is correct. The definition requires termination and correct output for every valid input, so one failing input disqualifies it.
Exercise
Rewrite "season to taste" as a definite step, and state what input and output your version needs.
Show answer
One possible answer: "Add salt 0.5 g at a time, stirring and measuring salinity after each addition, until the salinity reading is at least 0.8%." Input: the dish and a salinity meter. Output: a dish with salinity of at least 0.8%. Each step is now mechanical and has a clear stopping condition. Many answers are acceptable as long as no step needs judgement.