1. Recursion
Kasun Ranga Wijeweera
(Email: krw19870829@gmail.com)
Department of Statistics and Computer Science
Faculty of Science
University of Peradeniya
2. What is Recursion?
• A fundamental concept in computer science and mathematics
• A recursive program is one that calls itself
• There must be a termination condition
3. Recurrences
• Recursive definitions of functions are quite common in
mathematics
• The simplest type, involving integer arguments are called
recurrence relations
• Most familiar such a function is the factorial function, defined
by the formula
N ! = N * (N - 1) !, for N >=1 with 0 ! = 1
4. Recurrences
• The corresponding simple recursive program is as follows
int factorial (int N)
{
if (N == 0) return 1;
return N * factorial (N - 1);
}
• Problem:
factorial (-1) leads to an infinite loop
5. Recurrences
• A second well-known recurrence relation is the one that
defines the Fibonacci numbers
F (N) = F (N - 1) + F (N - 2), for N >= 2 with F (0) = F (1) =1
• This defines the sequence
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610,…
6. Recurrences
• The corresponding recursive program is as follows
int fibonacci (int N)
{
if (N <= 1) return 1;
return fibonacci (N - 1) + fibonacci (N - 2);
}
• The running time of this program is exponential
7. Recurrences
• To compute F (N) in linear time
#define max 25
int fibonacci (int N)
{
int i, F[max];
F[0] = 1; F[1] = 1;
for(i = 2; i <= max; i++)
F[i] = F[i - 1] + F[i - 2];
return F[N];
}
8. Divide and Conquer
• Most of the recursive programs use two recursive calls, each
operating on about half the input
• This is so called “divide and conquer” paradigm
• Used to achieve significant economics
• They normally do not reduce to trivial loops like the factorial
program
• They normally do not lead to excessive re-computing as
Fibonacci program, because the input is divided without
overlap
9. Divide and Conquer: Example
• Let us consider the task of drawing the markings for each inch
on a ruler
• There is a mark at the 1/2 point
• Slightly shorter marks at 1/4 intervals
• Still shorter marks at 1/8 intervals, etc
10. Divide and Conquer: Example
• Suppose the desired resolution is 1/(2^n)
• Put a mark at every point between 0 and (2^n), end points not
included
• A procedure mark (x, h) is used to mark h units high at x
position
• The middle mark should be n units high
• The marks in the left and right halves should be n-1 units high
11. Divide and Conquer: Example
• The relevant “divide and conquer” recursive program is as
follows
rule (int a, int r, int h)
{
int m = (a + r) / 2;
if (h > 0)
{
mark (m, h);
rule (a, m, h-1);
rule (m, r, h-1);
}
}