In general, an algorithm is a sequence of well-defined instructions for solving a particular problem. Originally, algorithms were part of mathematics – the word “algorithm” comes from the Arabic writer Muhammad ibn Musa al-Khwarizmi, – but currently it is usually associated with computer science and programming.

In terms of computer science, an algorithm is a finite sequence of unambiguous instructions for calculating a function (or executing a procedure) that terminates in a well-defined ending state. An algorithm has set of following properties:

• An algorithm is an unambiguous description that makes clear what has to be implemented. In a mathematical algorithm, a step such as “Choose a large number” is vague: what is large? 1 million, 1 billion, or 100?
• An algorithm expects a defined set of inputs. For example, it might require two numbers where both numbers are greater than zero. Or it might require a word, or a list of zero or more numbers.
• An algorithm produces a defined set of outputs. It might output the larger of the two numbers, an all-uppercase version of a word, or a sorted version of the list of numbers.
• An algorithm is guaranteed to terminate and produce a result, always stopping after a finite time. If an algorithm could potentially run forever, it wouldn’t be very useful because you might never get an answer.
• Most algorithms are guaranteed to produce the correct result. It’s rarely useful if an algorithm returns the largest number 99% of the time, but 1% of the time the algorithm fails and returns the smallest number instead.
• If an algorithm imposes a requirement on its inputs (called a precondition), that requirement must be met. For example, a precondition might be that an algorithm will only accept positive numbers as an input. If preconditions aren’t met, then the algorithm is allowed to fail by producing the wrong answer or never terminating.

## Example of an algorithm

Let’s say we need to find the largest number in list of numbers. Here is a description of an algorithm to do this.

Problem: Given a list of numbers, return the largest number on the list.

Inputs: A list L of positive numbers. This list must contain at least one number.

Outputs: A number n, which will be the largest number of the list.

Algorithm:

1. Set max to 0.
2. For each number x in the list L, compare it to max. If x is larger, set max to x.
3. max is now set to the largest number in the list.