CMSC202 Lecture Notes for week 6

Lecture 11 was actually Exam #1 Lecture 12 was part 1 of the discussion on recursion. Notes are available in the reading file for recursion

A topic not covered in the handouts was that of memoization which is something you'll see again in dynamic programming. The simple version of the fibonaccifunction, for example, has a most inefficient running time - as we will see later, as we compute the nth fib. number using that simple function, the run time to do so increases exponentially. We want to do better, and we can do so by saving the results of prior computations, thus avoiding the task of recomputing them.

Consider:

   int fib(int n) {
     if (n <2) return n; //assuming n is non-negative
     int table[n+1];  //create a table to hold the results we already have
     table[0] = 0;
     table[1]= 1;

     for (int x=2; x <= n; ++x)
        table[x]=-1;
    
    return fib_aux(table, n);
    }

   int fib_aux (int T[], int n){
      if (T[n] >= 0) return T[n];
      
      return (T[n] = fib_aux(T, n-1) +
                     fib_aux(T, n-2)    );
                
    }
The effect of this tabularization is that we compute each term of the sequence only one time instead of many, and the runtime efficiency of our algorithm improves to linear time.

Previous Lecture
Next Lecture


Last Modified: 30 Mar 1999 20:59:47 EST by Mitch Edelman edelman@cs.umbc.edu

Back up to Spring 1999 CMSC 202 Section Homepage