Recursion Recursive method Calls itself directly or indirectly

















- Slides: 17
Recursion • Recursive method – Calls itself (directly or indirectly) through another method – Method knows how to solve only a base case – Method divides problem • Base case • Simpler problem – Method now divides simpler problem until solvable – Recursive call – Recursive step – Related to mathematical induction
Factorials • N Factorial • N! = 1 * 2 * 3 *. . . * N • N! = N * (N-1)!, if N > 1 (recursive step) N! = 1, if N <= 0 (Base case) – A recursive definition – Relies on smaller computations
Fig. 15. 2 Recursive evaluation of 5!.
Factorials • See Figures 15. 3, 15. 4
The Fibonacci Series • Fibonacci series – Each number in the series is sum of two previous numbers • e. g. , 0, 1, 1, 2, 3, 5, 8, 13, 21… fibonacci(0) = 0 fibonacci(1) = 1 fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 1 ) • fibonacci(0) and fibonacci(1) are base cases – Golden ratio (golden mean)
Fig. 15. 7 Set of recursive calls for fibonacci (3).
Run Time Stack • Java uses a runtime stack to store parameters, variables, and other information • Each call to a method places an activation record on the runtime stack • A program using recursion will have multiple activation records for the same method on the stack – See Figure 15. 8, page 753 – See Figure 15. 9, page 754
Recursion vs. Iteration • Iteration – – Uses repetition structures (for, while or do…while) Repetition through explicitly use of repetition structure Terminates when loop-continuation condition fails Controls repetition by using a counter • Recursion – – Uses selection structures (if, if…else or switch) Repetition through repeated method calls Terminates when base case is satisfied Controls repetition by dividing problem into simpler one
Recursion vs. Iteration (cont. ) • Recursion – – More overhead than iteration More memory intensive than iteration Can also be solved iteratively Often can be implemented with only a few lines of code • Example – Iterative Fibonacci calculation, Fig 15. 10 – page 755
Permutations • For a given set, a permutation of the set is an ordering of the elements of the set – There are n! Permutations of a set containing n elements – What are they? How can they be computed? • Recursion! – See Figure 15. 12 -13, page 758 -760
Towers of Hanoi • Legend – 64 disks of increasing size – 3 pegs – Disks can only be placed on larger disks • How many Operations is required?
Fractals • A fractal is an object that is self-similar at all levels of scaling • Examples – – – Coastlines Trees Mandelbrot set Koch Curve/Snowflake Menger sponge
Coastlines
Trees
Mandelbrot Set
Koch Curve and Snowflake
Menger Sponge

















