1 / 9

Recursion

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. 5!. 1. 5!. 1.

joetta
Download Presentation

Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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

  2. 5! 1 5! 1 Final value = 120 5! = 5 * 24 = 120 is returned 5 * 4! 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 4 * 3! 3! = 3 * 2 = 6 is returned 3 * 2! 3 * 2! 2! = 2 * 1 = 2 is returned 2 * 1! 2 * 1! 1 returned (b) Values returned from each recursive call. (a) Sequence of recursive calls. Recursive evaluation of 5!.

  3. Example Using Recursion: 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) = 1fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 2 ) • fibonacci(0) and fibonacci(1) are base cases • Golden ratio (golden mean)

  4. fibonacci( 3 ) return fibonacci( 2 ) fibonacci( 1 ) + + return fibonacci( 1 ) fibonacci( 0 ) return 1 return 0 return 1 Set of recursive calls for fibonacci(3).

  5. Example Using Recursion: The Hanoi Tower

  6. Example Using Recursion: The Hanoi Tower

  7. Example Using Recursion: The Hanoi Tower

  8. 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

  9. 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

More Related