Recursion
Data Structures & Algorithms
Introduction
A programming technique in which a
function calls itself. One of the most effective techniques in programming.
What is recursion?
Sometimes, the best way to solve a problem
is by solving a smaller version of the exact same problem first Recursion is a technique that solves a problem by solving a smaller problem of the same type
When you turn this into a program, you end up with functions that call themselves (recursive functions)
int function(int x) { int y; if(x==0) return 1; else { y = 2 * function(x-1); return y+1; } }
Problems defined recursively
There are many problems whose solution
can be defined recursively Example: n factorial
n!= 1 (n-1)!*n 1 1*2*3**(n-1)*n if n = 0 if n > 0 if n = 0 if n > 0 (recursive solution)
n!=
(closed form solution)
Coding the factorial function
Recursive implementation
int Factorial(int n) { if (n==0) // base case return 1; else return n * Factorial(n-1); }
Iterative implementation
int Factorial(int n) { int fact = 1;
Coding the factorial function (cont.)
for(int count = 2; count <= n; count++) fact = fact * count; return fact; }