Upload
drusilla-hodges
View
251
Download
0
Embed Size (px)
Citation preview
The factorial function
n! =
1 ∙ 2 ∙ 3 ∙ … ∙ (n – 1) ∙ n
??
n! =
1 if n = 0 (base case, anchor)n ∙ (n – 1)! if n > 0 (inductive step)
Data Structures and Algorithms in Java, Third Edition Ch05–2
Application of the definition of n!
= 3 ∙ 2!
= 2 ∙ 1!
= 1 ∙ 0!
= ?
0!
= ?
= ?= 1 ∙ 1 = 1
= 2 ∙ 1 = 2
= 3 ∙ 2 = 6
3!
1!
2!
= 1
Data Structures and Algorithms in Java, Third Edition Ch05–3
Implementation of the factorial function
long factorial(long n) {
if (n == 0)
return 1;
else return n * factorial(n-1);
}
Data Structures and Algorithms in Java, Third Edition Ch05–4
Stack frame
parameters and local variables
return value
return address
Data Structures and Algorithms in Java, Third Edition Ch05–5
Executing the factorial method
long factorial(long n) { if (n == 0) return 1; else return n * factorial(n-1);}.............................void f() { ............................. long m = factorial(3); .............................}
(20)
(10)
Data Structures and Algorithms in Java, Third Edition Ch05–6
0
?
(10)
1
?
(10)
2
?
(10)
3
?
(20)
0
1
(10)
1
?
(10)
2
?
(10)
3
?
(20)
1
1
(10)
2
?
(10)
3
?
(20)
2
2
(10)
3
?
(20)
*
3
6
(20)
1
?
(10)
2
?
(10)
3
?
(20)
2
?
(10)
3
?
(20)
3
?
(20)
*
*
long factorial(long n) { if (n == 0) return 1; else return n * factorial(n-1);}.............................void f() { ............................. long m = factorial(3); .............................}
(20)
(10)
Data Structures and Algorithms in Java, Third Edition Ch05–7
Tracing recursion
void f(int n) { if (n > 0) { f(n-1); System.out.print(n + " "); f(n-1); }}
Data Structures and Algorithms in Java, Third Edition Ch05–8
Tracing recursion using indentationf(1) f(0) 1 f(0)
output: 1
f(3) f(2) f(1) f(0) 1 f(0) 2 f(1) f(0) 1 f(0) 3 f(2) f(1) f(0) 1 f(0) 2 f(1) f(0) 1 f(0)
output: 1 2 1 3 1 2 1
f(2) f(1) f(0) 1 f(0) 2 f(1) f(0) 1 f(0)
output: 1 2 1
void f(int n) { if (n > 0) { f(n-1); System.out.print(n + " "); f(n-1); }}
Tracing recursion using tree of calls
void f(int n) { if (n > 0) { f(n-1); System.out.print(n + " "); f(n-1); }}
f(1)
f(0) 1 f(0)
output: 1
f(2)
f(1) 2
f(0) 1 f(0)
output: 1 2 1
f(2)
f(1) 2 f(1)
f(0) 1 f(0) f(0) 1 f(0)
output: 1 2 1 3 1 2 1
f(2)
f(1) 2 f(1)
f(0) 1 f(0) f(0) 1 f(0)
f(3)
3
f(1)
f(0) 1 f(0)
Data Structures and Algorithms in Java, Third Edition Ch05–10
Excessive recursion5
2
4
1
3
0
4
2
3
1
3
2
2
2
2
1
2
0
1
0
1
1
1 1
2
1
1
0
1
1
1 1
11
3
1
2
1
2
0
1
0
1
1
1 1
1
1
n
k n-1
k-1
n-1
k+
=
1 if k = 0 or k = n
otherwise
Designing recursive methods: example
5 6 2 -3
-3?
2
65
?
+
11
+
13
+
10
Data Structures and Algorithms in Java, Third Edition Ch05–12