Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Recursion zPurpose:There are situations where iterative algorithms become too complicated and a more elegant solution would be helpful. You can design.

Similar presentations


Presentation on theme: "1 Recursion zPurpose:There are situations where iterative algorithms become too complicated and a more elegant solution would be helpful. You can design."— Presentation transcript:

1 1 Recursion zPurpose:There are situations where iterative algorithms become too complicated and a more elegant solution would be helpful. You can design an algorithmwhere it performs a simple task and that task it repeatedly called. zThis process is called recursion.

2 2 zResources: zJava Essentials Chapter 17 p.667 zJava Essentials Study Guide Chapter 14 p.221 zBarrons AP Java Chapter 17 p.219

3 3 zHandouts:Fibonacci.java z Factorial.java z combo.java z M/C Questions

4 4 zRecursive Functions: zFunctions whose code includes calls to itself zPossible because successive function calls create instances of the “stateful” properties of the function zA frame on the stack zThe function code is shared

5 5 zRecursive Functions: yThe system implements a function call the same way : whether the function calls itself or another function.

6 6 z3 Rules: yfind out how to take just 1 step ybreak each journey into 1 step plus a smaller journey (work towards the base case) yknow when to stop --- BASE CASE

7 7 zBase Case: yThe “regular line” yThe lowest level where no recursive calls are made yThe place where no recursive calls are made

8 8 zRecursive Case: yA repeat command

9 9 zRecursion & Iteration: yIteration explicitly uses a repetition structure (loops) yRecursion achieves repetition through repeated function calls

10 10 zRecursion & Iteration... Both involve a termination test: xIteration ends when loop fails xRecursion ends when a base case is recognized ( a simpler version of the original problem is produced until the base case is reached) yBoth can occur indefinitely if not designed correctly

11 11 zWhen NOT to use Recursion: yfunctions declaring large local arrays yfunctions that manipulate static vars, global vars or arrays yif performance is vital ywhen dealing with linear structures and processes (simple iterations are best)

12 12 zRecursion Drawbacks: yIt repeatedly invokes function calls onto the stack yExpensive in CPU time and memory

13 13 zWhen Recursion is Best Used: yUsed best when it significantly simplifies the code without excessive performance loss. yUseful for dealing with nested structures or branching processes yUsed in traversing tree structures

14 14 zSample Problem: A recursive algorithm for painting a square. Given a square If the length is less than 2 ft, stop Divide the square into 4 equal size squares Paint 1 of these small squares Repeat from the top for each of the 3 unpainted squares Square of 16 feet (256 square ft)

15 15 zSample Problem… How Many Squares Created & Painted... In the 1 st pass ? In the 2 nd pass ? In the 3 rd pass ? In the 4 th pass ? What is the TOTAL SQUARES Painted? Take some time now to try this...

16 16 zSample Problem: 1 st pass, four 8” squares 1p 3 up 2 nd, 12 4” squares 3p 9 up 3 rd, 36 2” squares, 9p 27up 4 th, 108 1” squares, 27p, 81up total painted = 1+ 3 + 9 + 27 = 40

17 17 zSIGMA Example zUse the following function shell to code for a recursive algorithm that SUMS INTEGERS FROM 1 to N

18 18 zSIGMA Example Int Sigma (int n) { }

19 19 Int Sigma (int n) { if (n <= 1) return n; else return n + Sigma(n-1); }

20 20 TPS: Convert and Print a Decimal number (100) to a binary number (base 2) 100 / 2 = 50 remainder 0 50 / 2 = 25 remainder 0 25 / 2 = 12 remainder 1 12 / 2 = 6 remainder 0 6 / 2 = 3 remainder 0 3 / 2= 1 remainder 1 1 / 2 = 0 remainder 1

21 21 Reading remainders in reverse order gives result: 1100100 the binary for 100 Write a Recursive solution: Identify the first step Break down step into a smaller version Know when to stop --- the base case (quotient <= 0) The last remainder must be the first printed

22 22 Here is the Shell Code: public static void convertToBinary(int dec) { }

23 23 ANS:Java Essentials Study Guide Chapter 14 p.222 public static void convertToBinary(int dec) { int quotient = decimalNum / 2; int remainder = decimalNum % 2; if (quotient > 0) { convertToBinary(quotient); // smaller version } System.out.println(remainder); // base case }

24 24 zFIBONACCI Example (handout) zCOMBO Example (handout) zREVERSE A SENTENCE

25 25 zEFFICIENCY “a measure of the runtime usage of computational processes” Select an instruction in the algorithm that executes more/less based on the size of the data (this process dominates the work)

26 26 zEFFICIENCY... Linear Behavior -- Number of instructions executed INCREASES PROPORTIONAL to the size of the data

27 27 zEFFICIENCY... Quadratic Behavior -- Number of instructions executed INCREASES PROPORTIONAL to the size of the data SQUARED Least Efficient of these

28 28 zEFFICIENCY... Logarithmic Behavior -- LOG 2 N MOST Efficient

29 29 zEFFICIENCY… Illustration Data Log2 Linear N log N Quadratic 1 11 1 1 10 410 40 100 100 7100 700 10,000 1,000 101,000 10,000 1,000,000 10,000 1410,000 140,000 100M

30 30 Efficiency… zExponential Growth O(a^n) zRecursive functions, like FIBONACCI, have an exponential order of growth zLets Run Fibonacci Recursively…..\recursion programs\fibonacci.exe

31 31

32 32 TPS (OPTIONAL):Permutations of a String (Java Essentials ch 17 p.672 - 676) Design a class that lists all the permutations of a string For example, the string “eat” has 6 permutations: eat eta aet ate tea tae Use the text for approach and code solution

33 33 TPS (OPTIONAL):GasPump (Java essentials Study Guide Vhapter 14 p.223-224) Write a recursive class that simulates the spinning of the digits on a gas pump Use the text for approach and code solution

34 34 zTips for the AP Exam: zThe AP Exam includes M/C questions that give a recursive algorithm and then ask about that algorithm zYou will need to be able to TRACE through a recursive process to obtain the answer

35 35 zTips for the AP Exam: zNever use a while statement when an if statement should be used to check for a base case in a recursive algorithm zAvoid infinite recursion by coding for a base case that WILL be reached

36 36 zTips for the AP Exam: zUnless the solution requires you to write a recursive solution OR the problem is stated in a recursive nature, code solutions ITERATIVLY

37 37 zTips for the AP Exam: zWhen there is ONE recursive call from “return”, use the STACK METHOD to help you resolve the code zExample, Factorial

38 38 zTips for the AP Exam: zWhen there are TWO recursive calls from “return”, use the BINARY TREE METHOD to help you resolve the code zExample, Combo & Fibonacci

39 39 zLAB: yFactorial yMaking Change yMultiple Choice Questions


Download ppt "1 Recursion zPurpose:There are situations where iterative algorithms become too complicated and a more elegant solution would be helpful. You can design."

Similar presentations


Ads by Google