Professional Documents
Culture Documents
07 Recursion PDF
07 Recursion PDF
Emphasis of recursion:
& %& %
and smaller pieces until you can solve it; combine
the results.
' $' $
CS211 — R ECURSION 1 CS211 — R ECURSION 2
Which Approach
Should You Choose?
Which is Better?a
Depends on the problem.
// assumes n>=0
“Programmers”, esp. w/o college CS training, often public static int fib (int n) f
prefer iterative solutions.
& %& %
Compare iterative to recursive versions of factorial! g
a Some of these statements are personal opinion.
& %& %
return n * factorial (n-1);
Moral: “Obvious” and “natural” solutions aren’t }
}
always practical.
' $' $
CS211 — R ECURSION 5 CS211 — R ECURSION 6
If you are not careful with the program logic, you may class RecursionTest {
miss a basis case and go off into an infinite recursion. // Find max value in an unsorted array of ints.
public static int findMax (int [] A, int startIndex) {
& %& %
}
! This is often pretty hard!
& %& %
}
make BSTs of more interesting entities if they support
ideas of lessThan/greaterThan. ...
' $' $
CS211 — R ECURSIVE BST S 1 CS211 — R ECURSIVE BST S 2
& %& %
Somewhat unintuitive.
& g
%& %
' $' $
CS211 — R ECURSIVE BST S 5 CS211 — M ORE R ECURSION 1
& %& %
}
}
return -1;
}
int soughtVal) {
Have a window or range of values we are currently int lo=0, hi=A.length-1;
considering.
// Exit loop when lo>hi. This will happen just
[Initially, the window is the whole array.] // after the sublist has been reduced to one
// element (lo==hi) and then we reset lo or hi
Look at midpoint in range and compare to soughtValue. // because we didn’t find soughtVal there.
while (lo <= hi) {
! If A[mid] == soughtValue, we’re found it. // note integer division.
!
final int mid = (lo + hi)/2;
If A[mid] < soughtValue, discard first half. if (A[mid] == soughtVal) {
// discard first half
Keep halving the list until either you find it or your lo = mid +1;
sublist has no elements. } else {
// discard second half
& %& %
Computational complexity of binary search is number
}
hi = mid -1;
' $' $
CS211 — M ORE R ECURSION 4 CS211 — M ORE R ECURSION 5
3 poles.
& %& %
! Can’t put larger ring on top of smaller.
System.out.println ("\nSoln for three rings:\n");
move (3, 1, 3); The set of params and local vars for a function call is
& %& %
} stored in an activation record (AR).
}
' $' $
CS211 — M ORE R ECURSION 8 CS211 — M ORE R ECURSION 9
&
CS211 — M ORE R ECURSION 10
%&
CS211 — M ORE R ECURSION 11
%