An algorithm is a precise, step-by-step procedure for solving a problem or performing a computation. It takes some input, follows a fixed sequence of well-defined operations, and produces an output in a finite amount of time.
The word comes from the name of the 9th-century Persian mathematician Muhammad ibn Musa al-Khwarizmi, whose works introduced systematic procedures for arithmetic and algebra to a wide audience. The idea is much older: Euclid’s method for finding the greatest common divisor, described around 300 BCE, is still taught and used today.
Every piece of software is built from algorithms. Sorting a list, routing a packet across a network, compressing a file, and ranking search results are all algorithmic problems.
How It Works
An algorithm is defined by what it does, not by the language it is written in. A computer program is one implementation of an algorithm. The algorithm itself is the underlying method.
The Five Properties
A procedure qualifies as an algorithm when it satisfies these properties:
- Input: It accepts zero or more well-defined inputs.
- Output: It produces at least one result that has a defined relationship to the input.
- Definiteness: Every step is precise and unambiguous. Two people following the steps must perform the same operations.
- Finiteness: It terminates after a finite number of steps for every valid input.
- Effectiveness: Every step is basic enough to be carried out exactly, in principle by a person with pencil and paper.
A recipe is a loose analogy, but many recipes fail definiteness (“add salt to taste”). An algorithm leaves no room for judgment calls.
Representing an Algorithm
Algorithms are commonly expressed in one of three forms:
- Natural language: Numbered steps in plain English.
- Pseudocode: Structured, language-neutral notation using constructs like
if,while, andfor. - Flowcharts: Diagrams of steps and decision points.
Pseudocode is the standard in textbooks because it removes syntax noise while preserving logic.
From Problem to Algorithm
Designing an algorithm generally follows this path:
- Specify the problem. State the exact input format and the required output.
- Choose a strategy. Common strategies include brute force, divide and conquer, greedy choice, dynamic programming, and backtracking.
- Define the steps. Write them precisely, covering edge cases such as empty input.
- Prove or test correctness. Show that the output is always right, not just for a few examples.
- Analyze efficiency. Measure how time and memory grow with input size.
Real-World Application
Euclid’s algorithm computes the greatest common divisor (GCD) of two integers. It relies on one observation:
Repeat this reduction until the second number is zero. The first number is then the GCD.
def gcd(a: int, b: int) -> int:
while b != 0:
a, b = b, a % b
return a
print(gcd(48, 18)) # 6
Tracing gcd(48, 18):
| Step | a | b | a mod b |
|---|---|---|---|
| 1 | 48 | 18 | 12 |
| 2 | 18 | 12 | 6 |
| 3 | 12 | 6 | 0 |
| 4 | 6 | 0 | — |
The loop stops when b reaches 0, and the answer is a = 6. This example shows all five properties:
- Input and output: It takes two integers and returns one.
- Definiteness: Each step is a single division with remainder.
- Finiteness: The remainder strictly decreases and is always non-negative, so the loop must end.
- Effectiveness: Every operation is basic arithmetic.
Beyond number theory, algorithms operate throughout everyday systems:
- Databases use B-tree search to find records without scanning every row.
- Operating systems use scheduling algorithms to decide which process runs next.
- Networks use shortest-path algorithms such as Dijkstra’s to route data.
- Security systems use cryptographic algorithms to hash passwords and encrypt traffic.
Trade-offs and Alternatives
A problem usually has many valid algorithms. The choice depends on how each one behaves as the input grows.
Measuring Efficiency
Computer scientists describe an algorithm’s cost using asymptotic notation, most often Big-O. It describes how running time or memory grows as the input size increases, ignoring constant factors and hardware details.
Searching a sorted list of items shows the difference:
| Algorithm | Approach | Time complexity |
|---|---|---|
| Linear search | Check every element in order | |
| Binary search | Halve the search range each step |
For a sorted list of one million items, linear search may need up to one million comparisons. Binary search needs at most about 20, because .
Euclid’s algorithm runs in time, which is why it stays fast even for very large integers.
Common Trade-offs
- Time vs. space: Caching results (memoization) speeds up computation but uses more memory.
- Simplicity vs. speed: A brute-force solution is easy to write and verify. An optimized one is faster but harder to get right.
- Exact vs. approximate: Some problems have no known fast exact algorithm. In those cases, approximation algorithms or heuristics return a good answer quickly without guaranteeing the best one.
- Average case vs. worst case: An algorithm that is fast on typical input may be slow on adversarial input. Choose based on what your system can tolerate.
[!NOTE] Big-O describes growth rate, not exact speed. For small inputs, an algorithm with low overhead can outperform an algorithm with high overhead. Practical libraries often switch strategies based on input size for this reason.
Algorithm vs. Heuristic vs. Program
- An algorithm is a finite procedure that, for valid inputs, solves the problem as specified.
- A heuristic is a rule of thumb that often works well but may give a suboptimal or wrong answer.
- A program is code that implements an algorithm (or several) on a specific platform.
Common Misconceptions and Gotchas
“An algorithm is just code.” Code is one expression of an algorithm. The same algorithm can be implemented in many languages, and a poorly written implementation can fail even when the underlying algorithm is correct.
“Faster on my machine means a better algorithm.” Measured time depends on hardware, language, compiler, and input size. Complexity analysis compares algorithms independently of those factors. Benchmarks and asymptotic analysis answer different questions, and good engineering uses both.
“Correct on the examples means correct.” Passing a handful of test cases does not prove correctness. Edge cases such as empty input, a single element, duplicates, negative numbers, and maximum-size input cause most real failures.
“Every algorithm works on any input.” Many algorithms have preconditions. Binary search, for example, requires sorted data. On unsorted input it returns wrong results silently, with no error.
[!WARNING] Violating an algorithm’s preconditions rarely raises an error. It usually produces plausible but incorrect output, which makes the bug hard to detect. Document and check preconditions explicitly.
“Big-O is the whole story.” Big-O hides constant factors, memory access patterns, and cache behavior. Two algorithms with the same complexity class can differ significantly in practice.
Forgetting termination. A loop whose condition never becomes false is not an algorithm, because it violates finiteness. Always identify a quantity that strictly progresses toward the stopping condition, as the remainder does in Euclid’s method.
Key Takeaways
- An algorithm is a finite, unambiguous sequence of effective steps that maps inputs to outputs. It is independent of any programming language.
- To qualify as an algorithm, a procedure needs input, output, definiteness, finiteness, and effectiveness.
- Correctness comes first, then efficiency. Efficiency is measured by how time and memory grow with input size, typically in Big-O notation.
- Multiple algorithms can solve the same problem. Choosing among them means weighing time, space, simplicity, and the guarantees you need.
- Check preconditions and edge cases, because most algorithmic bugs come from inputs the author did not consider.
Related articles in Computer Science
- Search, Planning, and Decision-Making — Learn state-space search, BFS, Dijkstra, A*, heuristics, automated planning, and sequential decisions in AI.