Outline for May 29, 2009
Reading: §13.4
- Recursion review
- Express problem in terms of itself
- Recursive definitions
- Base case (not recursive)
- Recursive part (must eventually reduce to base case)
- Example: number of positive numbers in a list (see
poslist.py)
- Definition
- Base case: empty list gives pos(lst) = 0
- Recursive part: if first element is positive,
pos(lst) = 1 + pos(lst[1:]);
otherwise, pos(lst) = pos(lst[1:])
- Show stack for lst = [ 3, -2, -1, 4 ]
- Example: greatest common denominator of m and n (see
rgcd.py)
- Definition
- Base case: if n is 0,
gcd(m, n) = m
- Recursive part: gcd(m, n) =
gcd(n, m % n)
- Show stack for m = 12, n = 8
- Example: Tower of Hanoi (see
hanoi.py)
- Definition
- Base case: 1 disk, just move it
- Recursive part: move n−1 disks to second pole,
move bottom disk to third, move disks on second pole to third
- Show stack for 3 disks
- Sorting
- Why it is important
- A bit of history
- Selection sort (see selsort.py)
- Scan list to find smallest element
- Swap it and first element
- Repeat for rest of list