SUNY Geneseo Department of Computer Science


Practice with Recurrence Relations

{Date}

CSci 141, Spring 2004
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Misc

First hour exam next Tuesday, March 2

Questions?

Timing worst case in lab: n = 25

Counting "elses" in analyzing algorithms?

Recurrence Relations

Section 7.2.2

Building a "bridge" between algorithm and recurrence function

Make functions for number of times algorithm executes something from algorithm

Steps

Same approach for implicit parameters

Can also use recurrence relations to determine abstract execution time

Recurrences become more useful as algorithms get more complicated

Practice with Recurrences

Here's an algorithm to move a robot n tiles forward, then bring it back to where it started, facing in its original direction. How many primitive robot messages (i.e., messages defined for Robot) does it send?

    // In some subclass of Robot...
    void forwardAndBack( int n ) {
        if ( n > 0 ) {
            this.move();
            this.forwardAndBack( n-1 );
            this.turnLeft();
            this.turnLeft();
            this.move();
            this.turnLeft();
            this.turnLeft();
        }
    } 

This algorithm computes the sum of the even numbers from n down to 2, given the preconditions that n is even and n >= 2:

    int sumEvens( int n ) {
        if ( n == 2 ) {
            return 2;
        }
        else {
            return n + sumEvens( n - 2 );
        }
    }

Next Lecture