SUNY Geneseo Department of Computer Science
{Date}
CSci 141, Spring 2005
Prof. Doug Baldwin
Section 7.2.2
Recursive algorithms can be converted into equations (recurrence relations)
Equations let us figure out how many steps algorithm executes as function of some number, n
Question: example that counts test in an "if"?
How many times does this send a "substring" message?
countSpaces( String str )
if str == ""
return 0
else if str.charAt(0) == ' '
return 1 + countSpaces( str.substring(1) )
else
return countSpaces( str.substring(1) )
How many primitive robot messages does this send, as a function of the robot's distance from the wall?
// In some subclass of Robot...
lineToWall()
if this.okToMove()
this.paint( green )
this.move()
this.lineToWall()
this.move()
else
this.turnLeft()
this.turnLeft()
How many times does this execute its "if n == 0" test?
isOdd( n )
if n == 0
return false
if n == 1
return true
else
return isOdd( n-2 )
n | f(n) |
---|---|
0 | 1 |
1 | 1 |
2 | 2 |
3 | 2 |
4 | 3 |
5 | 3 |