SUNY Geneseo Department of Computer Science


Recurrence Relations for Analyzing Algorithms, Part 2

{Date}

CSci 141, Fall 2003
Prof. Doug Baldwin

Return to List of Lectures

Previous Lecture


Questions?

Reading Summary

Finish reading Section 7.2.2

Expands on recurrence relations

More examples

More complex algorithms & their recurrences

Value-producing recursion

Execution time and 2-to-the-n example

Mini-Assignment

How many lines of output from

    manyMessages( int n )
        if ( n > 0 )
            System.out.println( "Hello world" )
            this.manyMessages( n-1 )
            this.manyMessages( n-1 )

Is it 2n?

f() = number of "hello world" messages manyMessages prints for a given parameter

Closed form? f(n) = n

No, f(2) doesn't work

n f(n)
0 0
1 1+2f(0) = 1
2 1 + 2f(1) = 1 + 2(1) = 3
3 1 + 2f(2) = 1 + 2(1 + 2(1)) = 1 + 2 + 2*2 = 7

Previous similar recurrences had closed forms of the form 2n - 1

Prove f(n) = 2n - 1 by induction on n

Other Examples

    class ExtendedArray

        private int data[]

        selectionSort( n )
            // put elements 0 .. n into ascending order
            if ( n > 0 )
                int maxPos = findMax( n )
                temp = data[n]
                data[n] = data[maxPos]
                data[maxPos] = temp
                this.selectionSort( n-1 )

        findMax( n )
            // get index of max value in positions 0 .. n
            if ( n > 0 )
                int prev = findLargest( n-1 )
                if ( data[n] > data[prev] )
                    return n
                else
                    return prev
            else
                return 0

Count comparisons in findMax, then plug that result into recurrence for selectionSort

findMax does n comparisons

For selectionSort, let C(n) = # comparisons selectionSort(n) does

Next

Applying many of the principles we've seen for algorithm design (e.g., recursion, object-oriented programming, induction, recurrences, experiments) to organizing data for efficient processing

Data structures


Next Lecture