What Is an Algorithm? Correctness, Cost and Data Structures
An algorithm is a finite, unambiguous sequence of steps that takes an input, produces an output, and stops. A recipe that says "add salt to taste" is not quite an algorithm, because two cooks can read it differently. "Compare each number with the largest one seen so far and keep the larger" is one: every step is precise, there are finitely many of them, and when the list runs out the procedure ends.
This guide covers what makes a procedure an algorithm, why correctness comes before speed, how two correct algorithms can cost very different amounts of work, and where data structures fit in. It ends with the order in which the rest of this site's guides take you through the subject.
The four properties
- Input. The algorithm works on some data: a list of numbers, a string, a graph. The set of inputs it is meant to handle should be stated, for example "a non-empty list of integers".
- Output. It produces a result with a clear relationship to the input, such as "the largest value in the list".
- Definiteness. Each step means exactly one thing. There is no "pick a good one" or "repeat until it looks right".
- Finiteness. It finishes after a finite number of steps for every valid input. A loop that can run forever on some input is a bug, not an algorithm.
Correctness first, then efficiency
An algorithm is correct if it gives the right output for every valid input, not just the inputs you happened to try. That includes the awkward ones: a list with one element, a list where the largest value appears twice, a list of negative numbers. A fast algorithm that is wrong on one input in a thousand is still wrong.
Only once two algorithms are both correct does it make sense to ask which is cheaper. "Cheaper" usually means fewer basic steps (time) or less extra memory (space), measured as a function of the input size. The Big O guide gives you the vocabulary for that comparison.
A worked example: the largest number in a list
In plain words. Write down the first number and call it the largest so far. Look at each remaining number in turn. If it is bigger than the largest so far, cross out the old value and write down the new one. When you reach the end of the list, the number you have written down is the answer.
Why is that correct? After you have looked at the first k numbers, the value you hold is the largest of those k. That statement is true at the start (k = 1) and each step keeps it true, so when k reaches the length of the list it is the largest of all of them. A statement like this, true before and after every pass of a loop, is called a loop invariant, and it is the usual way to argue that a loop is correct.
A second correct method: sort the list from smallest to largest and take the last element. Both give the same answer. They do not do the same amount of work.
Examples use Python 3.10 or later and only the standard library.
def largest_by_scan(numbers):
largest = numbers[0]
comparisons = 0
for i in range(1, len(numbers)):
comparisons += 1
if numbers[i] > largest:
largest = numbers[i]
return largest, comparisons
def largest_by_sorting(numbers):
ordered = sorted(numbers)
return ordered[-1]
data = [7, 42, 3, 19, 42, 8, -5, 30]
print(largest_by_scan(data))
print(largest_by_sorting(data))
print(largest_by_scan([-3]))
Output:
(42, 7)
42
(-3, 0)
The scan makes exactly n - 1 comparisons for a list of n numbers (7 for the 8-item list, 0 for a single item) and needs only one extra variable. Sorting a general list by comparisons needs on the order of n log n comparisons in the worst case, and sorted() builds a new list of n items. For 8 numbers the difference is invisible. For a million numbers the scan makes 999,999 comparisons, while n log2 n is already about 20 million. The scan is the better algorithm for this task, even though both are correct.
Notice the stated input: both functions assume a non-empty list. largest_by_scan([]) raises an IndexError on numbers[0]. Deciding what should happen on empty input (raise an error, return None) is part of specifying the algorithm, not an afterthought.
Check yourself. Would the scan still be correct if it started with largest = 0 instead of numbers[0]? Try it on [-3] before reading on. (It returns 0, which is not in the list: the "obvious" starting value breaks on all-negative input.)
What a data structure is
A data structure is a way of organizing data in memory so that certain operations are cheap. A Python list keeps items in order and lets you read position i in one step. A set keeps no order but can tell you whether it contains a value in constant time on average. A heap always knows its smallest item. None of them is better in general; each makes some operations fast by making others slower or by using more memory.
Algorithms and data structures are chosen together, because the structure changes the algorithm. Suppose you must answer many questions of the form "is x in my collection?":
- With an unsorted list, each question is a scan: up to n comparisons.
- With a sorted list, you can use binary search: about log2 n comparisons per question, but you paid to sort first and every insertion has to keep the order.
- With a set, each question takes constant time on average, at the cost of extra memory for the hash table.
The question is the same; the right algorithm depends on how the data is stored and on how often it changes. That is why this subject is usually taught as "algorithms and data structures", and why most of the later guides discuss both at once.
How the guides on this site are organized
The guides are written to be read roughly in this order. Each one assumes the ones before it.
- Analysis. Big O notation and growth rates, then time and space complexity, best, average and worst case, and amortized analysis. This is the language every later guide uses.
- Recursion. How recursion works, followed by recurrence relations, the master theorem and divide and conquer.
- Data structures. Starting from arrays and dynamic arrays and moving through linked lists, stacks and queues, hash tables, trees, heaps and graphs.
- Searching and sorting. Binary search, then the sorting algorithms compared side by side, with separate guides on the simple sorts, merge sort and quicksort, and counting and radix sort.
- Graph algorithms and design techniques. Breadth-first and depth-first search, shortest paths, minimum spanning trees, greedy algorithms, dynamic programming and backtracking.
- Putting it to work. Common bugs in algorithm code and a method for approaching an unfamiliar problem.
To get a feel for how quickly different growth rates pull apart before you start, the Big O Complexity Analyzer evaluates the usual growth functions (1, log n, n, n log n, n squared and so on) at an n you choose and ranks them. Its numbers are values of those formulas, not timings of real code, which is exactly the right way to think about Big O.
Summary
- An algorithm is a finite, unambiguous procedure from a stated input to an output, and it always stops.
- Correct means right on every valid input, including the edge cases; prove it with an invariant, test it with small awkward inputs.
- Among correct algorithms, compare the work they do as the input grows. Scanning for the maximum takes n - 1 comparisons; sorting first does more.
- The data structure you choose decides which algorithms are available and what they cost.