An algorithm is a method or procedure for carrying out a task (such as solving a problem in mathematics, finding the freshest produce in a supermarket, or manipulating information in general).
Algorithms are sometimes implemented as computer programs but are more often implemented by other means, such as in a biological neural network (for example, the human brain implementing arithmetic or an insect relocating food), or in electric circuits or in a mechanical device.
The analysis and study of algorithms is one discipline of computer science, and is often practiced abstractly (without the use of a specific programming language or other implementation). In this sense, it resembles other mathematical disciplines in that the analysis focuses on the underlying principles of the algorithm, and not on any particular implementation. One way to embody (or sometimes codify) an algorithm is the writing of pseudocode.
Some writers restrict the definition of algorithm to procedures that eventually finish. Others include procedures that could run forever without stopping, arguing that some entity may be required to carry out such permanent tasks. In the latter case, it can be difficult to determine whether a given algorithm successfully completes its tasks.
Here is a simple example of an algorithm.
Imagine you have an unsorted list of random numbers. Our goal is to find the highest number in this list. Upon first thinking about the solution, you will realize that you must look at every number in the list. Upon further thinking, you will realize that you need to look at each number only once. Taking this into account, here is a simple algorithm to accomplish this:
And here is a more formal coding of the algorithm in a pseudocode that is similar to most programming languages:
- Pretend the first number in the list is the largest number.
- Look at the next number, and compare it with this largest number.
- Only if this next number is larger, then keep that as the new largest number.
- Repeat steps 2 and 3 until you have gone through the whole list.
Given: a list "List"
counter = 1
largest = List[counter]
while counter <= length(List):
if List[counter] > largest:
largest = List[counter]
counter = counter + 1
Notes on notation:
As it happens, most people who implement algorithms want to know how much of a particular resource (such as time or storage) a given algorithm requires. Methods have been developed for the
- = as used here indicates assignment. That is, the value on the right-hand side of the expression is assigned to the container (or variable) on the left-hand side of the expression.
- List[counter] as used here indicates the counterth element of the list. For example: if the value of counter is 5, then List[counter] refers to the 5th element of the list.
- <= as used here indicates 'less than or equal to'