Iteration and Recursion - PowerPoint PPT Presentation

About This Presentation
Title:

Iteration and Recursion

Description:

Recursive Solution. procedure hanoi(n, A, B) if n==1. then move disk from A to B ... How does the Walsh algorithm represent the towers in Towers of Hanoi? ... – PowerPoint PPT presentation

Number of Views:184
Avg rating:3.0/5.0
Slides: 40
Provided by: Mik126
Learn more at: http://www.cs.ucf.edu
Category:

less

Transcript and Presenter's Notes

Title: Iteration and Recursion


1
Iteration and Recursion
  • Michael Prestia
  • COT 4810
  • February 7, 2008

2
Iteration
  • Straightforward
  • Instructions are processed in order they are
    received
  • Mutable state

3
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

4
(No Transcript)
5
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

6
(No Transcript)
7
Recursive 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
8
hanoi(3, A, B)
A
B
C
9
hanoi(3, A, B) hanoi(2, A, C)
hanoi(1, A, B) move disk from A to
B
A
B
C
10
hanoi(3, A, B) hanoi(2, A, C) Move
disk from A to C
A
B
C
11
hanoi(3, A, B) hanoi(2, A, C)
hanoi(1, B, C) move disk from B to
C
A
B
C
12
hanoi(3, A, B) move disk from A to B
A
B
C
13
hanoi(3, A, B) hanoi(2, C, B)
hanoi(1, C, A) move disk from C to
A
A
B
C
14
hanoi(3, A, B) hanoi(2, C, B) move
disk from C to B
A
B
C
15
hanoi(3, A, B) hanoi(2, C, B)
hanoi(1, A, B) move disk from A to
B
A
B
C
16
(No Transcript)
17
Buneman-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)
27
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
5
4
6
28
5
1
6
29
5
2
1
30
2
3
1
31
1
3
6
32
1
4
3
33
2
1
3
34
5
1
2
35
5
4
1
36
(No Transcript)
37
Summary
  • Iteration
  • Mutable state
  • Order of execution
  • Recursion
  • Immutable state
  • Time and space complexity

38
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.

39
Homework
  • What is one disadvantage of recursion?
  • How does the Walsh algorithm represent the towers
    in Towers of Hanoi?
Write a Comment
User Comments (0)
About PowerShow.com