An algorithm is a finite, unambiguous sequence of steps that transforms a given input into a required output and is guaranteed to stop. In programming, algorithms are the logic beneath every function, from sorting a list to routing a network packet, and they exist independently of any particular language or machine.
The study of algorithms asks two questions about each procedure: is it correct, and how much time and memory does it consume as the input grows. Those answers, expressed with tools such as Big O notation, decide whether a program that works on ten records still works on ten million.
The defining properties of an algorithm
A procedure qualifies as an algorithm only when it satisfies a small set of formal properties. The classic list, popularized by Donald Knuth, requires finiteness, definiteness, well-specified input and output, and effectiveness, meaning that each step is basic enough to be carried out exactly.
The table below summarizes these properties and what goes wrong when one of them is missing.
| Property | Requirement | Failure when missing |
|---|---|---|
| Finiteness | Terminates after a finite number of steps | Infinite loop, program never returns |
| Definiteness | Every step has exactly one interpretation | Different implementations give different results |
| Input | Zero or more values from a defined set | Undefined behavior on unexpected data |
| Output | At least one result related to the input | Procedure performs work with no usable result |
| Effectiveness | Each step is executable in principle by hand | Steps such as “pick the best option” cannot run |
A computational procedure that may run forever, such as an operating system event loop or a web server, is not strictly an algorithm, although each request it handles is processed by algorithms. The distinction matters in proofs: termination must be shown, not assumed.
How algorithms are expressed and proved correct
Algorithms are usually written in pseudocode or as flowcharts before they become source code, because the idea should be judged separately from the syntax of Python, C or Java. A single algorithm, for example binary search, can have dozens of implementations that differ in style but share the same steps and the same cost.
Correctness is established with reasoning, not only with tests. The standard tool is the loop invariant, a statement that holds before the loop, is preserved by every iteration and, combined with the exit condition, implies the desired result. Recursive algorithms are proved by mathematical induction on the input size, and termination is shown with a variant, a quantity that strictly decreases toward a bound.
- Partial correctness: if the algorithm stops, the output is right.
- Total correctness: partial correctness plus a proof that it always stops.
- Testing can reveal errors but, as Edsger Dijkstra observed, cannot prove their absence.
Measuring algorithm efficiency
Efficiency is measured as a growth rate, not as seconds on a particular computer. Time complexity counts basic operations as a function of input size n, and space complexity counts extra memory. Both are written in asymptotic notation: Big O gives an upper bound, Omega a lower bound and Theta a tight bound.
The following table shows common complexity classes, typical algorithms that fall into each and how they scale when n reaches one million.
| Class | Typical algorithm | Approximate steps for n = 1,000,000 |
|---|---|---|
| O(1) | Array index lookup, hash table access on average | 1 |
| O(log n) | Binary search in a sorted array | About 20 |
| O(n) | Linear search, finding a maximum | 1,000,000 |
| O(n log n) | Merge sort, heapsort, average quicksort | About 20,000,000 |
| O(n²) | Bubble sort, naive pair comparison | 10¹² |
| O(2ⁿ) | Brute-force subset enumeration | Infeasible |
Analysts also distinguish worst-case, average-case and best-case behavior. Quicksort runs in O(n log n) on average but degrades to O(n²) in the worst case on adversarial or already sorted input when the pivot is chosen naively. Amortized analysis averages the cost over a sequence of operations, which explains why appending to a dynamic array is O(1) despite occasional costly resizes.
Algorithm design paradigms
Most practical algorithms follow one of a few design paradigms, reusable strategies for breaking a problem into manageable work. Recognizing the paradigm that fits a problem is often the decisive step in finding an efficient solution.
| Paradigm | Core idea | Representative examples |
|---|---|---|
| Brute force | Try every candidate solution | Linear search, exhaustive password check |
| Divide and conquer | Split, solve parts recursively, combine | Merge sort, quicksort, binary search |
| Greedy | Take the locally best choice at each step | Dijkstra’s algorithm, Huffman coding |
| Dynamic programming | Store answers to overlapping subproblems | Edit distance, knapsack, shortest paths |
| Backtracking | Build candidates and abandon dead ends | Sudoku solvers, N-queens |
| Randomized | Use random choices for speed or simplicity | Randomized quicksort, Monte Carlo methods |
A greedy strategy is fast but correct only when the problem has the greedy-choice property; for coin change with arbitrary denominations it can return a suboptimal answer, while dynamic programming always finds the optimum at higher cost. Graph traversal methods such as breadth-first search and depth-first search are building blocks that many paradigms reuse.
Algorithms compared with related concepts
The word algorithm is often confused with neighboring ideas in software development. The comparison below separates them by what each one actually describes.
| Concept | What it describes | Relation to an algorithm |
|---|---|---|
| Program | Concrete code for a specific language and platform | Implements one or more algorithms |
| Data structure | Organization of data in memory | Determines which algorithms are efficient |
| Heuristic | Rule of thumb that usually gives a good answer | May lack guarantees of optimality or termination |
| Protocol | Rules for communication between parties | Uses algorithms for steps such as encryption |
| Model | Learned parameters in machine learning | Produced by a training algorithm, not one itself |
The pairing of algorithm and data structure is especially tight. Dijkstra’s algorithm with a binary heap runs in O((V + E) log V), whereas the same algorithm with a plain array takes O(V²), so the choice of structure changes the complexity without changing the logic.
Choosing an algorithm and avoiding common mistakes
Selecting an algorithm is an engineering trade-off among speed, memory, simplicity and guarantees. Asymptotic class matters most for large inputs, while constant factors and cache behavior dominate for small ones, which is why production sort routines switch to insertion sort for short subarrays.
| Mistake | Typical symptom | Remedy |
|---|---|---|
| Nested loops over large data | Job that slows quadratically as data grows | Use hashing or sorting to reach O(n log n) |
| Ignoring the worst case | Rare inputs cause timeouts or denial of service | Choose algorithms with guaranteed bounds |
| Off-by-one boundaries | Missed first or last element, infinite loops | State loop invariants and test edge cases |
| Unbounded recursion | Stack overflow on deep inputs | Convert to iteration or limit depth |
| Premature optimization | Complex code with no measurable gain | Profile first, then optimize hot paths |
Some problems have no known efficient algorithm. NP-hard problems such as the traveling salesperson problem are handled in practice with approximation algorithms or heuristics, and some questions, such as the halting problem, are provably undecidable, meaning no algorithm can solve them for all inputs.
In plain words
An algorithm is a recipe for solving a problem. It lists exact steps, in order, so that anyone or any computer following them gets the same result and eventually finishes.
Two recipes can make the same dish with very different effort. Looking for a name in a phone book by reading every page works, but opening it in the middle and halving the search each time is far quicker. Good algorithms save time and memory, and the savings grow enormously as the amount of data grows.
A real-world example
A developer at an online retailer maintains a nightly job that removes duplicate customer records from a table of two million entries. The original code compared every record with every other record, an O(n²) approach requiring roughly two trillion comparisons, and the job had begun running past its four-hour window.
The developer replaced the nested loops with a single pass that stores a normalized email address in a hash set and flags any address already present. Each lookup takes constant time on average, so the job became O(n) and finished in under two minutes. The logic of what counts as a duplicate did not change; only the algorithm did, which removed the need for the extra server the team had planned to buy.