What Is an Algorithm?
A clear introduction to algorithms, with a short example and the idea of efficiency.
An algorithm is a finite, ordered sequence of clear steps for solving a problem or completing a task. A recipe, a set of directions and a long-division method are everyday examples.
Properties of a good algorithm
- Clear: every step is unambiguous.
- Finite: it ends after a limited number of steps.
- Correct: it produces the right result for valid inputs.
- General: it solves a whole class of problems, not just one case.
Ways to describe an algorithm
- Plain steps: a numbered list in everyday language.
- Pseudocode: structured text that resembles code but is not tied to a language.
- Flowchart: a diagram with boxes and arrows.
Example: find the largest number in a list
- Set largest to the first number.
- For each remaining number:
- If it is greater than largest, set largest to it.
- After the last number, largest holds the maximum.
In Python:
numbers = [4, 9, 2, 7]
largest = numbers[0]
for n in numbers[1:]:
if n > largest:
largest = n
print(largest) # prints 9
Searching: linear and binary
- Linear search checks items one by one. It works on any list.
- Binary search works only on a sorted list. It checks the middle item, then discards the half that cannot contain the target, repeating until found. For a sorted list of 1,000 items it needs at most about 10 comparisons, because 2¹⁰ = 1,024.
Efficiency
Computer scientists compare algorithms by how their running time or memory use grows as the input grows. This is often described with big-O notation. For example, linear search is O(n) and binary search is O(log n).
Common mistakes
- Writing steps that are vague, such as "do the calculation".
- Forgetting to explain what happens when the input is empty.
- Using binary search on unsorted data.
Quick recap
An algorithm is a precise, finite series of steps. Describe it with steps, pseudocode or flowcharts, and judge it by correctness and efficiency.