Recursion
Recursion
Recursion
• Recursion is an implicit application of STACK ADT.
• A recursive function is a function that calls itself to solve a smaller
version of its task until a final call is made which does not require a
call to itself.
• Every recursive solution has two major cases: the base case in
which the problem is simple enough to be solved directly without
making any further calls to the same function.
• Recursive case, in which first the problem at hand is divided into
simpler subparts. Second the function calls itself but with subparts
of the problem obtained in the first step. Third, the result is
obtained by combining the solutions of simpler sub-parts.
Types of Recursion
• Any recursive function can be characterized based on:
Recursion
Indirec Linea
Direct Tree Tail
t r
Direct Recursion
• A function is said to be directly recursive if it explicitly calls itself.
• For example, consider the function given below.
FIB(6) FIB(5)
FIB(2) FIB(1)
Pros and Cons of Recursion
Pros
• Recursive solutions often tend to be shorter and simpler than
non-recursive ones.
• Code is clearer and easier to use.
• Follows a divide and conquer technique to solve problems.
• In some (limited) instances, recursion may be more efficient.
Cons
• For some programmers and readers, recursion is a difficult
concept.
• Recursion is implemented using system stack. If the stack space on
the system is limited, recursion to a deeper level will be difficult to
implement.
• Aborting a recursive process in midstream is slow.
• Using a recursive function takes more memory and time to
execute as compared to its non-recursive counterpart.
• It is difficult to find bugs, particularly when using global variables.
Tower of Hanoi
Tower of Hanoi is one of the main applications of a recursion. It says, "if you can solve
n-1 cases, then you can easily solve the nth case"
A B C A B C
If there is only one ring, then simply move the ring from source to the destination
A B C
A B C A B C
A B C
A B C
A B C
A B C A B C
A B C
A B C A B C
Algorithm to move n disks from A
to C using B as auxiliary
1. If n=1, move single disk from A to C & stop
2. Move top n-1 disks from A to B using C as
auxiliary
3. Move the remaining disk from A to C
4. Move the n-1 disks from B to C using A as
auxiliary
void towers(int n, char from, char to, char aux)
{
if (n==1)
{ printf(“move disk 1 from %c to %c”, from, to);
return;
}
towers(n-1, from, aux, to)
printf(“move disk %d from %c to %c”, n, from, to);
towers(n-1, aux, to, from);
}