VIEWS: 2 PAGES: 39 POSTED ON: 8/18/2012
Michael Prestia COT 4810 February 7, 2008 Iteration Straightforward Instructions are processed in order they are received Mutable state Recursion 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 Towers of Hanoi 3 Towers Variable number of rings Move all rings to another tower Larger ring can never be placed on a smaller ring Recursive Solution procedure hanoi(n, A, B) if n==1 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 hanoi(3, A, B) A B C hanoi(3, A, B) hanoi(2, A, C) hanoi(1, A, B) move disk from A to B A B C hanoi(3, A, B) hanoi(2, A, C) Move disk from A to C A B C hanoi(3, A, B) hanoi(2, A, C) hanoi(1, B, C) move disk from B to C A B C hanoi(3, A, B) move disk from A to B A B C hanoi(3, A, B) hanoi(2, C, B) hanoi(1, C, A) move disk from C to A A B C hanoi(3, A, B) hanoi(2, C, B) move disk from C to B A B C hanoi(3, A, B) hanoi(2, C, B) hanoi(1, A, B) move disk from A to B A B C Buneman-Levy Solution procedure tower repeat move smallest disk clockwise move second smallest disk to remaining tower until all disks are on one peg B A C B A C B A C B A C B A C B A C B A C B A C B A C Walsh 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 4 6 5 1 6 5 2 1 5 3 1 2 3 6 1 4 3 1 1 3 2 1 2 5 4 1 5 Summary Iteration Mutable state Order of execution Recursion Immutable state Time and space complexity References 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. Homework What is one disadvantage of recursion? How does the Walsh algorithm represent the towers in Towers of Hanoi?
Pages to are hidden for
"Iteration and Recursion"Please download to view full document