Lecture 5
Lecture 5
Recursi
Algorithms on
Lecture 5
What is
Recursion?
The handshake
There are n peopleproblem
in a room. If each person shakes hands once with every
other person. What is the total number h(n) of handshakes?
We can see a recursive nature in the problem.
n-th person has (n-1) choices and after
n-th person chooses a person, problem recurs for n-1.
handshake(n) = (n-1) + handshake(n-1)
Base case:
handshake(0) = 0
h(n) = h(n-1) + n-1
h(4) = h(3) + 3
h(3) = h(2) + 2
h(2) = 1
The handshake
problem
We can come up with a direct formula by expanding the recursion.
We could write:
6! = 6 * 5!
Factorial
function
In general, we can express the factorial function as follows:
n! = n * (n-1)!
Stopping/Base Condition
Factorial function
(cont.)
FACT (n)
{
if n > 1
return n * FACT(n-1);
else
return 1;
}
recursion means that a
function calls itself
Tracing
Recursion
Function call stack and
activation record
F1 () F2 (b) F3 (c)
a = 10 a = 10 + b a = 10 + c
F2(a) c = F3(a) return a
…. return c
Tracing
Recursion
int factorial (int num)
{
if (num > 1)
return num * factorial(num-1);
else
return 1;
}
Factorial
function
For certain problems (such as the factorial function), a recursive solution often leads to
short and elegant code. Compare the recursive solution with the iterative solution:
Iterative solution
Recursive solution
fac(numb)
{ product=1;
factorial (num)
{ while(numb>1){
if (num > 1) product *= numb;
return num * factorial(num-1); numb--;
else }
return 1; return product;
} }
Recursion is
costly
We have to pay a price for recursion:
• calling a function consumes more time and memory than adjusting a loop counter.
• high performance applications (graphic action games, simulations of nuclear explosions)
hardly ever use recursion.
result = 1; Oops
while(result >0){ !
...
result++;
}
Oops
!
Recursion and base
condition
Similarly, if we use recursion we must be careful
not to create an infinite chain of function calls:
fac(numb){
return numb * fac(numb-1);
Oops
} No !
Or: terminati
on
fac(numb){ condition
if (numb<=1)
return
1;
else
} return numb
*
Oops
Recursion and base
condition
• Recursion is one way to decompose a task into smaller subtasks. At
least one of the subtasks is a smaller example of the same task.
• The smallest example of the same task has a non-recursive
solution.