What is an algorithm?
The key idea
An algorithm is a precisely described method for solving a class of problems. It specifies steps and conditions so the intended result can be obtained from allowed inputs. Code is one way to implement that method in a programming language.
For a beginner, a useful algorithm description includes the input, required output, assumptions and stopping rule. “Find the answer” is a goal; it is not yet a method.
Define a small problem
Given a non-empty finite list of comparable numbers, return its largest value. Our example is 7, 3, 9, 2. The expected result is 9.
The word non-empty matters because an empty list has no largest element under this problem definition. A program must reject that case or use a separately defined result policy rather than invent a value silently.
Write the steps independently of the language
- Set the current largest value to the first element.
- Visit each remaining element.
- If the element is greater than the current largest, replace the current largest.
- After the final element, return the current largest.
| Element just considered | Largest so far |
|---|---|
| 7 | 7 |
| 3 | 7 |
| 9 | 9 |
| 2 | 9 |
Initialising from the first element also handles a list containing only negative numbers. Starting from zero would fail for that case.
Explain why the method works
After each step, the current largest equals the largest value among the elements already visited. This statement is an invariant: it stays true as the process advances.
It is true after the first element. Each comparison either keeps the existing largest or replaces it with a greater value, so it remains true. Once every element has been visited, the largest among visited elements is the largest in the whole list.
This explanation is stronger than “it worked on my example.” It connects the steps to the required result.
Separate correctness from efficiency
For n elements, the method makes n - 1 comparisons after initialisation and uses a fixed amount of extra storage for the current largest. These observations concern the method, not the number of seconds it takes on one computer.
A different task, such as finding a value in sorted data, may permit a different approach. The next algorithm should follow the next problem's conditions.
Practise the distinctions
The list is the data. Its representation is a data-structure choice. The comparison procedure is the algorithm. A C or C++ program is an implementation.
Gammal Tech's Algorithms course requires Data Structures. Before advancing, try the method on a one-element list, equal values and negative values. Explain both why it stops and why the result is correct.
References and course details
Use these references for further study. The examples and exercises in this article are educational; consult the catalogue for course details.