Title: Iteration and Recursion
1Iteration and Recursion
- Michael Prestia
- COT 4810
- February 7, 2008
2Iteration
- Straightforward
- Instructions are processed in order they are
received - Mutable state
3Recursion
- Breaks a problem down into self-similar
sub-problems - How it works
- Function calls itself
- Instance pushed onto stack
- Once base condition is reached, pop from stack
- Immutable state
4(No Transcript)
5Towers of Hanoi
- 3 Towers
- Variable number of rings
- Move all rings to another tower
- Larger ring can never be placed on a smaller ring
6(No Transcript)
7Recursive Solution
procedure hanoi(n, A, B) if n1 then move
disk from A to B else hanoi(n-1, A, C)
move disk from A to B hanoi(n-1, C, B)
A
B
C
8hanoi(3, A, B)
A
B
C
9hanoi(3, A, B) hanoi(2, A, C)
hanoi(1, A, B) move disk from A to
B
A
B
C
10hanoi(3, A, B) hanoi(2, A, C) Move
disk from A to C
A
B
C
11hanoi(3, A, B) hanoi(2, A, C)
hanoi(1, B, C) move disk from B to
C
A
B
C
12hanoi(3, A, B) move disk from A to B
A
B
C
13hanoi(3, A, B) hanoi(2, C, B)
hanoi(1, C, A) move disk from C to
A
A
B
C
14hanoi(3, A, B) hanoi(2, C, B) move
disk from C to B
A
B
C
15hanoi(3, A, B) hanoi(2, C, B)
hanoi(1, A, B) move disk from A to
B
A
B
C
16(No Transcript)
17Buneman-Levy Solution
procedure tower repeat move
smallest disk clockwise move second
smallest disk to remaining tower until all
disks are on one peg
18(No Transcript)
19(No Transcript)
20(No Transcript)
21(No Transcript)
22(No Transcript)
23(No Transcript)
24(No Transcript)
25(No Transcript)
26(No Transcript)
27Walsh Solution
1. Move smallest disk onto even disk 2. if all
disks are on the same peg then exit else move
second disk onto other disk go to 1
n 1
n 3
n 2
5
4
6
285
1
6
295
2
1
302
3
1
311
3
6
321
4
3
332
1
3
345
1
2
355
4
1
36(No Transcript)
37Summary
- Iteration
- Mutable state
- Order of execution
- Recursion
- Immutable state
- Time and space complexity
38References
- Dewdney, A.K. The New Turing Omnibus. New York
Henry Hold and Company, 1993 - Knowlton, Todd. Introduction to Computer Science
Using C. Cincinnati South-Western Educational
Publishing, 1998.
39Homework
- What is one disadvantage of recursion?
- How does the Walsh algorithm represent the towers
in Towers of Hanoi?