RECURSION
Recursion is somewhere defined as the tool to fast iteration, whereas some people find it obfuscating and detest it with proof of it being slow and occupancy of unnecessary space. Recursion is not something which occurs to us directly or naturally. We generally tend to think inward to a concluding point, and come out with the result. Proper recursion on the other hand is like moving outward to the circumference of the circle and jump back into the centre. This may make no sense, so let’s move to the implementation.
Recursion is defined as a process in which a function calls itself directly or indirectly, resulting into an iterative process.
Every recursive call consists of two phases :: A winding phase and an unwinding phase.
In winding the function is called till the base condition, which is defined as the terminating condition, as in from the time it is encountered, the function starts returning values. Usually a base value of 1 is returned. Thus the last winding call till the base case is found to have a definite value, and the value is used to calculate for the unwinding phase.
In the unwinding phase, each call to the last function call returns a value and it is operated on to calculate a value which gives the current value of the called function in the winding phase.
Visually a factorial of 5 would be ::
G(5)=5*G(4)
G(4)=4*G(3)
G(3)=3*G(2)
G(2)=2*G(1)
G(1)=1
G(2)=2*1
G(3)=3*2*1
G(4)=4*3*2*1
G(5)=5*4*3*2*1
Thus every recursive program has to have a return and a base statement. The base statement determines the end of the winding phase and the return returns values into a stack for computation in future. Thus a function overhead is continuously worked with in this case. Sometimes managing these overheads becomes a cumbersome process and iteration seems better than a recursive execution.
This can be solved with a little modification in the recursive call parameters. Instead of passing one direct value, we pass the calculated value along with it. This omits the need for a winding phase.
Such a recursion is called Tail recursion.
In a Tail recursion, the last statement in the winding phase returns the result. As the result is passed into each function call, there is no need for the function to be pushed into the stack and provide space for a calculated value. Thus, a tail recursion would function for a factorial as ::
G(5,1)= G(4,5)
G(4,5)= G(3,20)
G(3,20)= G(2,60)
G(2,60)= G(1,120)
G(1,120)= 120.
Thus, the extra overhead of the function is reduced by half, and is the actual proper implementation of a recursion.
Recursion finds help in cases requiring inductive data sets where subprograms exist which are based on initially iterative calls. Thus there are some cases where the data set changes internally and recursion is the only way to solve these problems with a standard logic and simple iteration makes the logic even more complicated.
