SUNY Geneseo Department of Computer Science


Recurrence Relations and Algorithms, Part 1

{Date}

CSci 141, Spring 2005
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Questions?

Recurrence Relations and Algorithms

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"?

For Example....

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

Next Lecture