Chapter5: Recursion: CSD201 - Data Structures and Algorithms (In C++)
Chapter5: Recursion: CSD201 - Data Structures and Algorithms (In C++)
C++)
Chapter5: Recursion
http://www.fpt.edu.vn/ 1
Chapter topics
• Concepts
• Implementation
http://www.fpt.edu.vn/ 2
The factorial function
n! = 1 ∙ 2 ∙ 3 ∙ … ∙ (n – 1) ∙ n
??
http://www.fpt.edu.vn/ 3
Application of the definition of n!
3! = 3 ∙ 2! = 3
?∙2=6
2! = 2 ∙ 1! = 2
?∙1=2
1! = 1 ∙ 0! ==?1 ∙ 1 = 1
0! = 1
http://www.fpt.edu.vn/ 4
Implementation of the factorial function
long factorial(long n) {
if (n == 0)
return 1;
else return n * factorial(n-1);
}
http://www.fpt.edu.vn/ 5
Stack frame
parameters
and local
variables
return value
return
address
http://www.fpt.edu.vn/ 6
Executing the factorial method
long factorial(long n) {
if (n == 0)
return 1;
(10) else return n * factorial(n-1);
}
.............................
void f() {
.............................
(20) long m = factorial(3);
.............................
}
http://www.fpt.edu.vn/ 7
Applications of queues
long factorial(long n) {
if (n == 0)
return 1;
(10) else return n * factorial(n-1);
}
.............................
void f() {
.............................
0 0 long m = factorial(3);
? 1 (20).............................
}
(10) (10)
1 1 1 * 1
? ? ? 1
(10) (10) (10) (10)
2 2 2 2 2 * 2
? ? ? ? ? 2
(10) (10) (10) (10) (10) (10)
3 3 3 3 3 3 3 * 3
? ? ? ? ? ? ? 6
(20) (20) (20) (20) (20) (20) (20) (20)
http://www.fpt.edu.vn/ 8
Tracing recursion
void f(int n) {
if (n > 0) {
f(n-1);
System.out.print(n + " ");
f(n-1);
}
}
http://www.fpt.edu.vn/ 9
Tracing recursion using indentation
f(1) f(3)
f(2)
f(0) f(2)
f(1)
1 f(1)
f(0)
f(0) f(0)
1
1
f(0)
output: 1 f(0)
2
2
f(1)
f(1)
f(0)
f(0)
1
1
f(0)
f(0)
3
output: 1 2 1
f(2)
f(1)
f(0)
1
f(0)
void f(int n) { 2
if (n > 0) { f(1)
f(n-1); f(0)
System.out.print(n + " "); 1
f(n-1); f(0)
}
} output: 1 2 1 3 1 2 1
http://www.fpt.edu.vn/ 10
Tracing recursion using tree of calls
f(1) f(2)
f(3) output: 1 2 1
f(2) 3 f(2)
output: 1 2 1 3 1 2 1
void f(int n) {
if (n > 0) {
f(n-1);
System.out.print(n + " ");
f(n-1);
}
}
http://www.fpt.edu.vn/ 11
Excessive recursion n
1 if k = 0 or k = n
= n-1 n-1
k otherwise
5 +
k-1 k
2
4 4
1 2
3 3 3 3
0 1 1 2
1 2 2 2 2 2 2
0 1 0 1 1 2
1 1 1 1 1 1 1 1 1
0 1 0 1 0 1
1 1 1 1 1 1
Designing recursive methods: example
5 6 2 -3
5 6
11
? 2
13
? -3
10
http://www.fpt.edu.vn/ 13
Designing recursive methods: example (continued)
http://www.fpt.edu.vn/ 14
Q&A
http://www.fpt.edu.vn/ 15