1
COMP 250
Lecture 11
recursive algorithms 1
- Oct. 2, 2017
recursive algorithms 1 Oct. 2, 2017 1 Example 1: Factorial - - PowerPoint PPT Presentation
COMP 250 Lecture 11 recursive algorithms 1 Oct. 2, 2017 1 Example 1: Factorial (iterative) ! = 1 2 3 1 factorial( n ){ // assume n >= 1 result = 1 for (k = 2; k <= n; k++) result = result * k
1
2
3
4
5
6
7
8
9
fibonacci( 247 ) fibonacci( 246 ) fibonacci( 245 ) fibonacci( 245 ) fibonacci( 244 ) fibonacci( 244 ) fibonacci( 243) fibonacci( 244 ) fibonacci( 243) fibonacci( 243 ) fibonacci( 242) etc
10
11
12
13
14
Problem: Move n disks from start tower to finish tower such that:
a bigger disk onto a smaller disk)
15
16
17
move from A to C move from A to B move from C to B
18
19
Somehow move 4 disks from A to C move 1 disk from A to B Somehow move 4 disks from C to B
20
21
tower( 4, A, C, B ) tower( 1, A, B, C) tower( 4, C, B, A)
22
23
tower( 1, start, finish, other ) tower( 0, start, other, finish) tower( 0, other, finish, start ) move start to other
24
tower( 2, start, finish, other ) tower( 1, start, other, finish) tower( 1, other, finish, start ) move move move
move from A to C move from A to B move from C to B
25
tower( 3, start, finish, other ) tower( 2, start, other, finish) tower( 2, other, finish, start ) move move move move move move move
26
tower( n, start, finish, other ) tower( n – 1, start, other, finish) tower( n – 1, other, finish, start ) move move move move move move move … … … … … … …
27
mB mC mA mA mA mA mA main main main main main main main
28
factorial(1) factorial(2) factorial(2) factorial(2) factorial(3) factorial(3) factorial(3) factorial(3) factorial(3) main main main main main main main
29
30
31
parameters in current stack frame Call stack for TestTowerOfHanoi
32