Академический Документы
Профессиональный Документы
Культура Документы
Lecture Objectives
• Recursion
Process of solving a problem by reducing it to smaller
versions of itself
• Recursive definition
Definition in which a problem is expressed in terms of a
smaller version of itself
Has one or more base cases
Recursive Definitions (Cont’d)
0! = 1 (By Definition!)
n! = n x (n – 1) ! If n > 0
3! = 3 x 2!
2! = 2 x 1!
1! = 1 x 0!
0! = 1 (Base Case!)
1! = 1 x 0! = 1x1=1
2! = 2 x 1! = 2x1=2
3! = 3 x 2! = 3x2=6
Recursive Definitions (Cont’d)
• Recursive algorithm
Algorithm that finds the solution to a given problem by
reducing the problem to smaller versions of itself
Has one or more base cases
Implemented using recursive methods
• Recursive method
Method that calls itself
• Base case
Case in recursive definition in which the solution is
obtained directly
Stops the recursion
Recursive Definitions (Cont’d)
• General solution
Breaks problem into smaller versions of itself
• General case
Case in recursive definition in which a smaller
version of itself is called
Must eventually be reduced to a base case
Recursive Definitions (Cont’d)
• Recursive method
Logically, you can think of a recursive method having
unlimited copies of itself
Every recursive call has its own
• Code
• Set of parameters
• Set of local variables
Tracing a Recursive Method (Cont’d)
System.out.println(largest(list, 0, 3));
Execution of largest(list, 0, 3) (Cont’d)
public static void moveDisks(int count, int needle1, int needle3, int needle2) {
if (count > 0) {
moveDisks(count - 1, needle1,
needle2, needle3);
System.out.println("Move disk " + count
+ " from needle "
+ needle1 + " to needle "
+ needle3 + ". ");
moveDisks(count - 1, needle2,
needle3, needle1);
}
}
Recursion or Iteration?
private void drawSierpinski(Graphics g, int lev,Point p1, Point p2, Point p3) {
Point midP1P2;
Point midP2P3;
Point midP3P1;
if (lev > 0) {
g.drawLine(p1.x, p1.y, p2.x, p2.y);
g.drawLine(p2.x, p2.y, p3.x, p3.y);
g.drawLine(p3.x, p3.y, p1.x, p1.y);
midP1P2 = midPoint(p1, p2);
midP2P3 = midPoint(p2, p3);
midP3P1 = midPoint(p3, p1);
drawSierpinski(g, lev - 1, p1, midP1P2,midP3P1);
drawSierpinski(g, lev - 1, p2, midP2P3, midP1P2);
drawSierpinski(g, lev - 1, p3, midP3P1, midP2P3);
}
}
Programming Example: Sierpinski Gasket (Cont’d)
• Recursive definitions
• Recursive algorithms
• Recursive methods
• Base cases
• General cases
Lecture Summary (Cont’d)