Algorithm is a method that can be used by a computer for the solution of a problem. Algorithm is a sequence of instructions written in simple English language for solving a particular problem. The algorithm is independent of any programming language.
Properties of the Algorithm
- Finiteness: An algorithm must always terminate after a finite number of steps.
- Definiteness: Each step of an algorithm must be precisely defined: the actions to be carried out must be rigorously and unambiguously specified for each case.
- Input: An algorithm has zero or more inputs; that is, quantities which are given to it initially before the algorithm begins.
- Output: An algorithm has one or more outputs; that is, quantities which have a specified relation to the inputs.
- Effectiveness: An algorithm is also generally expected to be effective. This means that all of the operations to be performed in the algorithm must be sufficiently basic that can in principle be done exactly and in a finite length of time.
Simply, An algorithm is a procedure or step-by-step instruction for solving a problem. They form the foundation of writing a program.
For writing any programs, the following has to be known:
- Tasks to be performed.
- Output expected.
Complexity of an Algorithm: It is very convenient to classify algorithms based on the relative amount of time or relative amount of space they require and specify the growth of time/space requirements as a function of the input size. Thus, we have the notions of:
- Time Complexity: Running time of the program as a function of the size of input.
- Space Complexity: Amount of computer memory required during the program execution, as a function of the input size.
Example of an Algorithm: The following example of algorithm to check whether a number is positive or negative.
Step 1) : Read n, where n is any number.
Step 2) : If n>0, then write n is positive number.
else, n is negative number.
Step 3) : Stop.
Example of an Algorithm: The following example of algorithm to find the factorial of a given number.
Step 1) : Read n.
Step 2) : Set Fact = 1, I = 1.
Step 3) : Fact = Fact * I.
Step 4) : I = I + 1.
Step 5) : If I > n, write Fact
Else go to Step 3).
Step 6) : Stop.