What Is an Algorithm?
Precise recipes, judged by whether they are right and how they scale.
Sort a million numbers the way most people first think of, by repeatedly picking out the smallest one left, and you make about 500 billion comparisons. Merge sort makes fewer than 19 million. At a rule-of-thumb simple steps per second, that is more than an hour against a fifth of a second: the algorithm matters more than the machine.
What you’ll learn
- Say what makes a procedure an algorithm, and what a data structure is for.
- Compare linear and binary search by counting their steps, and explain why binary search needs sorted data.
- Compare growth rates with big-O intuition, and find the largest input a growth rate handles in a second.
- Explain how a loop invariant shows that an algorithm is correct, and why tests alone cannot.
- Read a problem's constraints to rule out algorithms that are too slow.
Precise enough for a machine
An algorithm is a finite list of precise steps that, for every valid input, stops and produces the right output. Every word in that sentence does work. Finite: you can write it down. Precise: a machine with no judgment can follow it. Stops and right: on every valid input, not just on the ones you tried.
The oldest algorithm still in daily use finds the greatest common divisor (gcd) of two whole numbers, the largest number that divides both: the gcd of 48 and 18 is 6. The obvious method tries every candidate. Euclid's algorithm, written down around 300 BC, uses one fact instead. Write for the remainder when is divided by . The pairs and have exactly the same common divisors, so the bigger pair can be swapped for the smaller one without changing the gcd.
def gcd_brute(a, b): # a, b >= 1
d = min(a, b)
while a % d != 0 or b % d != 0:
d -= 1 # not a common divisor: try the next one down
return d
def gcd_euclid(a, b): # a, b >= 0, not both 0
while b != 0:
a, b = b, a % b # same common divisors, smaller numbers
return aIn Python, a % b is . gcd_brute(48, 18) tries 18, 17, 16, …, 6: thirteen candidates. gcd_euclid(48, 18) needs three rounds, traced below.
| Round | |||
|---|---|---|---|
| 1 | 48 | 18 | 12 |
| 2 | 18 | 12 | 6 |
| 3 | 12 | 6 | 0 |
| stop | 6 | 0 | , so the answer is |
Think first How many candidates does gcd_brute try for 1,000,000 and 999,999? How many rounds does gcd_euclid need?
Any common divisor of two consecutive numbers also divides their difference, 1, so the gcd is 1, and the brute force tries all 999,999 candidates down to 1. Euclid needs two rounds: , then . Both functions are correct. Their costs are worlds apart.
Every algorithm therefore faces two questions, and this whole course is about answering them. Is it correct on every valid input? And how does its cost grow as the input gets bigger? Donald Knuth called Euclid's method "the granddaddy of all algorithms, because it is the oldest nontrivial algorithm that has survived to the present day." It is correct, and its cost barely grows. The next steps show how to measure that.
Searching: one by one, or by halves
You have 16 numbers in sorted order and want to know where 37 is. Linear search checks the cells one by one from the left: up to 16 comparisons. Binary search looks at the middle cell first. Because the numbers are sorted, that one comparison tells it which half could hold 37, and the other half is never looked at again.
Each probe halves the range that is still possible. Try it: you play the algorithm.
Binary search runs on a sorted list of 1,000,000 numbers. At most how many probes can it need?
Show the answer
20 probes
Each probe that misses halves what is left: 1,000,000, then 500,000, then 250,000, and after 19 probes at most one cell remains, because . One more probe checks it: at most probes. A linear scan may need all 1,000,000, and doubling the list adds just one probe to binary search.
The number of times you can halve before reaching 1 is the logarithm , and it grows very slowly: about 10 for a thousand, 20 for a million, 30 for a billion.
But binary search works only because the numbers are kept sorted. Arranging data so that the operations you need are fast is the job of a data structure, and every arrangement has a price: a sorted array is fast to search, but inserting a new number means shifting every larger one to make room.
Count steps, not seconds
How fast is binary search? A stopwatch measures the computer, the language and the input as much as the algorithm. Instead, count the simple steps as a function of the input size . Linear search makes up to comparisons, binary search about , and what matters is how those counts grow with .
Two habits make counts easy to compare. Keep only the fastest-growing term, and drop constant factors, which depend on the machine anyway. An algorithm that takes steps is "of order ", written in big-O notation: at the term is 3,000,000 steps and the rest only 5,007. Unless we say otherwise, we count the worst case, the most steps on any input of size , because that is a guarantee.
| Growth | Name | Typical example |
|---|---|---|
| constant | read the item at a given position | |
| logarithmic | binary search | |
| linear | linear search; the largest item of a list | |
| linearithmic | merge sort | |
| quadratic | compare every pair of items | |
| exponential | try every subset of the items | |
| factorial | try every ordering of the items |
A program whose running time grows like takes 1 second when . About how many seconds will it take when ?
Show the answer
100 seconds
Ten times the input means times the steps, so about 100 seconds. On the same tenfold input, an program would take 10 times longer, and an one about 12.5 times, because grows too, from about 13.3 to 16.6.
Is it right?
A fast wrong answer is worthless. Tests help, but they only sample the inputs. As Edsger Dijkstra wrote in 1970, "program testing can be used to show the presence of bugs, but never to show their absence!" A list of 20 numbers can arrive in different orders, and no test suite tries them all.
So algorithms are proved correct, and the workhorse is the loop invariant: a statement that is true before a loop starts and stays true after every round. When the loop stops, the invariant says that the job is done.
Insertion sort sorts the way many people sort a hand of cards. Its invariant: the left part of the array is sorted. Each round picks up the next key, slides it left past every larger key, and the sorted part grows by one. When the sorted part is the whole array, the array is sorted.
The Optimized lesson Correctness: Invariants & Proofs turns this into a method: how to find an invariant, how to prove it, and how to prove that a loop stops at all.
Algorithms that call themselves
Some algorithms are easiest to state in terms of themselves. The Fibonacci numbers 0, 1, 1, 2, 3, 5, 8, 13, … each add the two before them, so the recursive function writes itself: fib(n) = fib(n - 1) + fib(n - 2), with fib(0) = 0 and fib(1) = 1 as base cases that stop the calls.
It is obviously correct. Is it fast?
Without memory, fib(6) makes 25 calls, and the count grows by a factor of about 1.6 each time goes up by one: fib(40) makes 331,160,281 calls. With memoization, storing each answer the first time it is computed, the same recursion makes calls. The Optimized lesson Recursion & Recurrences shows how to count calls like these with an equation, a recurrence, and how to solve it.
Reading the constraints
In a contest or an interview, the problem statement tells you how fast your algorithm must be. Read the limit on and do the arithmetic: at about simple steps per second (a rule of thumb for compiled code) and a time limit of 1–2 seconds, allows steps easily, but rules out , which would take about 100 seconds.
So the constraints are a hint. Read backward, they give a complexity budget:
| up to about | Fits in about a second | Typical idea |
|---|---|---|
| 10–11 | try every ordering | |
| 20–25 | try every subset | |
| 500 | three nested loops | |
| 5,000 | look at every pair | |
| sort, then scan; a binary search per item | ||
| one pass | ||
| more | or | a formula, or binary search on the answer |
A sorted list of numbers comes with questions, each asking whether some number is in the list. Which approach fits in about a second?
- Scan the whole list for every question
- Sort the list again before every question
- Precompute something for every pair of numbers, then answer each question instantly
- Binary search for each question
Show the answer
D. Binary search for each question
Binary search needs at most probes per question, steps for all of them. The list is already sorted, and that is the signal: sorted data and many lookups → binary search.
The four Optimized lessons of this topic turn each idea of this lesson into a working tool:
| Optimized lesson | What you will do there |
|---|---|
| Big-O Notation & Running Time | Define , and exactly, count the steps of nested and halving loops, and estimate what fits in a time limit. |
| Correctness: Invariants & Proofs | Prove loops correct with invariants, prove that they stop, and prove recursive algorithms correct by induction. |
| Recursion & Recurrences | Turn recursive code into an equation that counts its work, and solve it with recursion trees and the master theorem. |
| Amortized Analysis | Prove that rare expensive steps average out, with the aggregate, accounting and potential methods. |
Key takeaways
- An algorithm is a finite, precise procedure that stops with the right output on every valid input; a data structure arranges data so that the operations you need are fast.
- Every algorithm faces two questions: is it correct, and how does its cost grow with the input size ? Euclid's algorithm and a brute-force search find the same gcd at wildly different costs.
- Count steps, not seconds: keep the fastest-growing term and drop constant factors, so steps is , and quote the worst case as a guarantee.
- Binary search on sorted data needs at most probes, 20 for a million items, where a linear scan may need all of them.
- Correctness comes from invariants, not from tests: a statement that holds before a loop and after every round says, when the loop ends, that the job is done.
- At about simple steps per second, rules out but allows , and exponential algorithms stop near .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A procedure returns the right answer on every input you have tested, but on some valid inputs it never stops. Is it an algorithm for the problem?
- Yes: every answer it gives is right
- Yes, as long as those inputs are rare
- No: an algorithm must stop with the right output on every valid input
- It depends on how fast the computer is
Show the answer
C. No: an algorithm must stop with the right output on every valid input
Stopping is part of the definition. On an input where the procedure runs forever it gives no answer at all, so it does not solve the problem, however rare such inputs are. Proving that a loop stops is a separate part of every correctness proof.
Algorithm A takes steps on inputs of size , and algorithm B takes steps. Which is faster?
- A, for every
- B for , and A for
- B, for every , because 100 is a large constant
- Neither: constants do not matter, so they are equally fast
Show the answer
B. B for , and A for
exactly when . Below that, B is faster; above it, A wins by more and more: at , A takes steps and B takes . Big-O ignores the constant 100 because for large inputs the growth rate decides.
Insertion sort has just finished placing the fifth key of a list. What is guaranteed at this moment?
- The first five places hold the first five keys of the list, in sorted order
- The five smallest keys of the whole list are in the first five places
- The whole list is sorted
- The fifth key is now in its final place
Show the answer
A. The first five places hold the first five keys of the list, in sorted order
Insertion sort's invariant is that the left part of the array is sorted. It rearranges only the keys it has already picked up, so the first five places hold exactly the original first five keys, sorted among themselves. Later keys can still slide in between them.
A problem has and a time limit of 1 second. Which is the fastest-growing running time you can safely afford?
Show the answer
D.
steps, a few hundredths of a second at steps per second. steps would take about 80 seconds, and and are beyond any time limit.
Why is the plain recursive fib(n), which returns fib(n - 1) + fib(n - 2), so slow?
- Recursion is always slower than a loop
- It recomputes the same smaller values again and again
- The numbers it adds become very large
- Its call stack grows to frames
Show the answer
B. It recomputes the same smaller values again and again
fib(6) computes fib(2) five separate times, and the repetition compounds as grows. With memoization each value is computed once, and the same recursion makes only calls.
Go deeper
- Big-O Notation & Running Time · Counting steps, comparing growth rates, and knowing what fits in a second.
- Correctness: Invariants & Proofs · Loop invariants, induction and termination: knowing an algorithm works before you run it.
- Recursion & Recurrences · Functions that call themselves, and the equations that count their cost.
- Amortized Analysis · Why an expensive step now and then still averages out: aggregate, accounting and potential.
Further reading
- D. E. Knuth, The Art of Computer Programming, Vol. 1: Fundamental Algorithms, 3rd ed. (Addison-Wesley, 1997), §1.1, "Algorithms".
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapters 1–3.