There is one Russian wooden doll. A large doll. If you open the head, a less large doll is found inside. If you take out the second doll and open it, another small doll appears. If you open the third doll, another smaller one is found. This goes on up to seven or eight dolls.
Suppose, you want to do some 'operation' with the dolls. That is, you want to label each doll. Take out all the dolls one by one. Fix the label on the smallest one and put it inside doll which slightly bigger. Label the second doll and repeat the operations till you label the biggest one.
This operation is laborious to do. But we can write the command for the operation concisely as given below.
Do
"label the doll and also label the doll inside"
Repeat
until no doll is found.
There is a computer algorithm by name 'Recursion' similar to this concept.
Suppose, you want to sum the natural numbers from 1 to N. You can write the command as follows.
Define sum(N) = 1+2+......+N
Hence we can write the computer command as:
sum(N)= N+ sum (N-1) if N is not equal to 0
When the computer encounters this command, it will magically sum the 1 to N numbers. Let us see how it works.
Let N=10
So sum(10)= 10 +sum (10-1)
but sum (10-1)= sum(9)
The computer will interpret the sum(9) as
sum(9)= 9+sum (9-1)
Because of back-reference in the sum(N) command
This will go on till N=0. Now the computer has stripped down sum(10) command and reached the innermost command sum(1) . Next the computer will execute the commands from sum(1) to sum(10) (from bottom up) and get you the sum 55 That is it, you are the master and the computer is the slave.
Recursion algorithm saves lot of memory space and speed up the execution.
The recursion can be applied to factorial, searching. find GCD, construct fractals etc.
Recursion is the important technique in the computer programming.
Comments
Post a Comment