Introduction to the Algorithm Theory Track
An algorithm is a finite, precisely described procedure that turns an input into an output. You have used plenty of them: every sort call, every hash-map lookup, every route a navigation app finds. This track is about the questions you ask after you have an algorithm. Does it always give the right answer? How much time and memory does it need as the input grows? Is there a fundamentally faster way, or is this the best anyone can do?
The Data Structures & Algorithms course on this site shows how the classic algorithms work. This track proves why they work and measures what they cost, with the same mix of explanation, step-through animations and runnable Python. This first course, Foundations of Algorithm Analysis, builds the toolkit every later course uses.
The map of the track
The track follows the topic order of the standard graduate-level textbook Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein (often called CLRS), then continues into research-level topics. The book is a map of topics only: every explanation, example, proof and exercise here is written from scratch.
| Part | Course | What it adds |
|---|---|---|
| I | Foundations of Algorithm Analysis (this course) | correctness proofs, step counting, asymptotic notation, recurrences, probabilistic analysis |
| I | Sorting and Order Statistics | heapsort, quicksort, lower bounds for comparison sorting, linear-time sorting, selection |
| I | Data Structures | hashing, search trees, red-black trees, B-trees, union-find |
| I | Design Techniques | dynamic programming, greedy algorithms, amortized analysis |
| I | Graph Algorithms | traversals, shortest paths, spanning trees, flows, matchings |
| I | Selected Topics | FFT, string matching, parallelism, NP-completeness |
| II | Advanced courses | randomized, approximation, online, streaming and parameterized algorithms, linear programming, spectral graph theory |
Each course assumes the ones before it. Inside this course, the sections build in order too: correctness first, then exact costs, then the notation that hides unimportant details, then the two big analysis techniques of Part I, recurrences and probability.
What you should already know
The course page lists three prerequisites. Here is what each one is needed for.
- Python. Every example is a short, self-contained Python program you can edit and run in the page. Nothing beyond lists, loops, functions and the standard library is used.
- Data structures and algorithms at the first-course level. You should have met arrays, linked lists, stacks, binary search and a couple of sorting algorithms, as in Insertion Sort and Time Complexity.
- Discrete mathematics. Proofs by induction, sums, a first look at asymptotic notation and expectation. This course revisits each of these from the algorithm designer's side and links back when it relies on a result proved there.
How to read pseudocode in this track
Algorithms are written twice: once in pseudocode, which is meant for people and for proofs, and once in Python, which is meant for running. The pseudocode uses a few fixed conventions.
FIND-MAX(a) // a is an array of n >= 1 numbers
1 best = a[0] // "=" assigns; "==" compares
2 for i = 1 to n - 1 // both ends included
3 if a[i] > best
4 best = a[i]
5 return best- Indices start at 0, as in Python. is the element at position , and is the length of the array.
- A slice means positions to , exactly like Python's
a[i:j]. So is the whole array and is empty. for i = 1 to n - 1includes both ends; in Python it becomesrange(1, n). A loopfor i = n - 1 downto 0counts down.- Indentation shows the block structure, and the numbered lines let a proof or a cost table refer to "line 4".
- Variables are local to the procedure, arrays are passed by reference (changes are visible to the caller), and
//starts a comment.
The Python version of FIND-MAX is a line-by-line translation:
def find_max(a):
best = a[0]
for i in range(1, len(a)):
if a[i] > best:
best = a[i]
return best
print(find_max([31, 41, 59, 26, 53, 58, 97, 93]))
print(find_max([-4]))97
-4
Notation used throughout
| Notation | Meaning |
|---|---|
| logarithm base 2, | |
| natural logarithm, base | |
| , | round down, round up |
| running time (number of steps) on an input of size | |
| , , | upper, lower and tight asymptotic bounds (the Asymptotic Notation section) |
| , | probability of an event, expected value of a random variable |
| the harmonic number |
A first taste: counting instead of timing
Algorithm analysis predicts cost by counting steps, not by reading a stopwatch. A stopwatch measures one program on one machine on one day; a step count is a property of the algorithm itself. Here are two ways to find a value in a sorted list, with a counter for the number of comparisons with list elements.
def linear_search(a, x):
steps = 0
for i, v in enumerate(a):
steps += 1
if v == x:
return i, steps
return -1, steps
def binary_search(a, x):
lo, hi, steps = 0, len(a), 0
while lo < hi:
mid = (lo + hi) // 2
steps += 1
if a[mid] < x:
lo = mid + 1
else:
hi = mid
found = lo < len(a) and a[lo] == x
return (lo if found else -1), steps
for n in [10, 1000, 1_000_000]:
a = list(range(0, 2 * n, 2)) # n sorted even numbers
x = a[-1] # the last one: worst case for linear search
_, s1 = linear_search(a, x)
_, s2 = binary_search(a, x)
print(f"n = {n:>9,}: linear {s1:>9,} comparisons, binary {s2:>2}")n = 10: linear 10 comparisons, binary 3
n = 1,000: linear 1,000 comparisons, binary 10
n = 1,000,000: linear 1,000,000 comparisons, binary 20
In C++
Throughout the track the core algorithms also come in C++, under an In C++ heading, printing the same output so that the two versions can be compared line by line. Here are the same two searches; C++ only needs a small helper for the thousands separators:
#include <cstdio>
#include <string>
#include <vector>
// adds thousands separators, like Python's f"{n:,}"
std::string commas(long long n) {
std::string s = std::to_string(n);
for (int i = (int)s.size() - 3; i > 0; i -= 3) s.insert(i, ",");
return s;
}
int linear_search(const std::vector<int>& a, int x, long long& steps) {
steps = 0;
for (int i = 0; i < (int)a.size(); i++) {
steps++;
if (a[i] == x) return i;
}
return -1;
}
int binary_search(const std::vector<int>& a, int x, long long& steps) {
int lo = 0, hi = (int)a.size();
steps = 0;
while (lo < hi) {
int mid = (lo + hi) / 2;
steps++;
if (a[mid] < x) lo = mid + 1;
else hi = mid;
}
bool found = lo < (int)a.size() && a[lo] == x;
return found ? lo : -1;
}
int main() {
for (int n : {10, 1000, 1000000}) {
std::vector<int> a(n);
for (int i = 0; i < n; i++) a[i] = 2 * i; // n sorted even numbers
int x = a.back(); // worst case for linear search
long long s1, s2;
linear_search(a, x, s1);
binary_search(a, x, s2);
std::printf("n = %9s: linear %9s comparisons, binary %2lld\n",
commas(n).c_str(), commas(s1).c_str(), s2);
}
}n = 10: linear 10 comparisons, binary 3
n = 1,000: linear 1,000 comparisons, binary 10
n = 1,000,000: linear 1,000,000 comparisons, binary 20
Multiplying the input size by 1,000 multiplies linear search's work by 1,000 but adds only about 10 steps to binary search, because binary search halves the range each time and needs about halvings. That difference, between growing like and growing like , is exactly what asymptotic notation captures. By the end of this course you will be able to derive such counts exactly, express them compactly and prove they are right.
How each lesson is built
Most lessons follow the same pattern, so you always know where to look:
- Intuition, often with an animation or an interactive lab you can play with first.
- Definitions and pseudocode, with formulas typeset as mathematics.
- A runnable implementation whose printed trace matches the animation.
- Analysis: why it is correct and what it costs. Longer proofs sit in collapsible "Proof sketch" boxes.
- Test yourself: a few quiz questions. The course quiz page collects all of them.
The examples are deterministic: anything random uses a fixed seed, so the output under each example is exactly what you will see when you run it. Change the seed, the sizes or the code, and run again. Experimenting is the fastest way to make a bound feel real.
Test yourself
In this track's pseudocode, what does the slice contain?
- Positions 2, 3, 4 and 5
- Positions 2, 3 and 4
- Positions 3, 4 and 5
- The elements with values 2 to 5
What does mean in this track?
- Any logarithm, the base is unspecified
Why does algorithm analysis count steps instead of measuring seconds?
- Seconds cannot be measured in Python
- A step count belongs to the algorithm, while a time depends on the machine, language and load
- Step counts are always smaller numbers
- Timing is only allowed for sorting algorithms
Binary search on 1,000 sorted values made 10 comparisons. About how many does it need on 1,000,000 values?
- About 10
- About 20
- About 10,000
- About 1,000,000