The Department of Computer Science & Engineering
cse@buffalo
STUART C. SHAPIRO: CSE 115 C

CSE 115
Introduction To Computer Science for Majors I
Lecture C
Lecture Notes
Stuart C. Shapiro
Spring, 2001


Recursion

Reading
Barnes, Section 10.10

Reminder: the three key control structures are sequence, selection, and loop.

We have discussed while, do, and for loops.

These are all versions of iterative loops.
Performing an interative loop is called iteration.

We will now discuss recursive loops.
Performing a recursive loop is called recursion.

Example: Fibonacci numbers (Leonardo Fibonacci, 1202)
You buy a newborn pair of rabbits on the first day of month 0. This breed of rabbits start producing young on the first day of of their 2nd month of life, and produce one pair of rabbits each month from then on. These rabbits also never die. How many pairs of rabbits will there be on the first day of month n?
Notice, on the first day of month n, all the rabbits from the previous month are still alive, and all the rabbits that were alive two months ago breed another pair.

Month:012345678
Number:112358132134

In general,
Fibonacci(n) = 1if n<2
  Fibonacci(n-1) + Fibonacci(n-2)if n>=2

public int Fibonacci(int n){
    if (n<2) return 1;
    else return Fibonacci(n-1) + Fibonacci(n-2);
}

See the example Fibonacci Numbers code.

Some other examples:

int Factorial(int x) {
    if (x<2) return 1;
    else return x*Factorial(x-1);
}

int gcd(int x, int y){ //Euclid
    if (x>y) return gcd(y,x);
    else if (x==0) return y;
    else return gcd(x, y%x);
}

Recursive Sorting (Insertion Sort)

Pseudocode:

To sort a[0 .. max] {
   if max == 0 {done;}
   else {
      sort a[0 .. max-1];
      insert a[max] into a[0 .. max];
   }
}

To insert x into a[0 .. max] {
   /* Assumes a[0..max-1] is sorted and a[max] is available. */
   if max == 0 or a[max-1] <= x {
      a[max] = x;
   }
   else {
   a[max] = a[max-1];
   insert a[max] into a[0 .. max-1];
   }
}

See the example Sorting code.

Additional topics introduced in the example code:

Use of objects (here, ColomnComparitors) to encapsulate methods.
ColomnCountComparitor and ColomnCategoryComparitor are two ColomnComparitors that both have a beforeOrEqual method, but implement them differently.
They are used only to give the two SortButtons different methods of comparing HistogramColumns.
This is the Object-Oriented version of treating functions (methods) as "first-class" objects, i.e. objects that can be assigned to variables and passed to methods.

See the example Graphing code.

First Previous Next

Copyright © 2001 by Stuart C. Shapiro. All rights reserved.

Stuart C. Shapiro <shapiro@cse.buffalo.edu>