The Department of Computer Science & Engineering |
STUART C. SHAPIRO: CSE
115 C
|
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: | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
---|---|---|---|---|---|---|---|---|---|
Number: | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 |
In general,
Fibonacci(n) | = | 1 | if 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, ColomnComparitor
s) to encapsulate
methods.
ColomnCountComparitor
and
ColomnCategoryComparitor
are two
ColomnComparitor
s that both have a
beforeOrEqual
method, but implement them differently.
They are used only to give the two SortButton
s different
methods of comparing HistogramColumn
s.
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.