/
Recursion For some problems, it’s useful to have a Recursion For some problems, it’s useful to have a

Recursion For some problems, it’s useful to have a - PowerPoint Presentation

myesha-ticknor
myesha-ticknor . @myesha-ticknor
Follow
342 views
Uploaded On 2019-12-18

Recursion For some problems, it’s useful to have a - PPT Presentation

Recursion For some problems its useful to have a method call itself A method that does so is known as a recursive method A recursive method can call itself either directly or indirectly through another method ID: 770834

public method recursive factorial method public factorial recursive fibonacci string recursion sentence number int return stack static long main

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "Recursion For some problems, it’s usef..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Recursion For some problems, it’s useful to have a method call itself. A method that does so is known as a recursive method. A recursive method can call itself either directly or indirectly through another method.

E.g. Add numbers in a range Raise number to a power Linear search Fibonacci method Factorial method Towers of Hanoi Merge sort Binary search Quick sort

Q: how to write a recursive method to add numbers from 0 to n? Public int add(n)

Q: How do you modify code to add range of values from n1(start) to n2(end)?

Q: Can you think of a different recursive implementation for previous?

Recursion A recursive method always contain a base case(s): The simplest case that method can solve . If the method is called with a base case, it returns a result . A recursive method always contain a recursive step(s ): If the method is called with a more complex problem , it breaks problem into same but simpler sub-problems and recursively call itself on these smaller sub-problems. The recursion step normally includes a return statement which allow the method to combine result of smaller problems to get the answer and pass result back to its caller .

Recursion For the recursion to eventually terminate , each time the method calls itself with a simpler version of the original problem, the sequence of smaller and smaller problems must converge on a base case . When the method recognizes the base case , it returns a result to the previous copy of the method.

Recurrence Relations Sum(s, f)     Add2 Add3 Power(b, e)   b e = b.b e-1 b e = b e/2 .b e/2  

Factorial Example Using Recursion: Factorial factorial of a positive integer n , called n! n! = n · (n – 1) · (n – 2) · … · 1 1! =1 0! =1 E.g. 5! = 5.4.3.2.1 = 120 4! = 4.3.2.1 = 24

Programming Question Write a iterative (non-recursive) method factorial in class FactorialCalculator to calculate factorial of input parameter n. Call this in the main method to print factorials of 0 through 50 A sample output is below:

Answer: Try setting n=100 in main. How does the output change? How does the output change when data type is int ? public class FactorialCalculator { public static int factorial (int n ) { int f= n; for(int i =(int )n ;i >=1 ;i--) f*= i; return f; } public static void main(String args[]) { for(int n=0;n<=100;n++) System.out.println(n+"!= +factorial (n)); } }

Factorials values grow quickly. Better choice for data type of f is long public static long factorialIterative ( long n) { long factorial = n; for( long i= n;i>=1;i--) factorial *= i; return factorial; }

How to write it recursively? Recursive aspect comes from : n! = n.(n-1)! E.g. 5!

Programming Question Modify FactorialCalculator factorial method to have a recursive implementation.   Recurrence Relation:

Answer public class FactorialCalculator { public static long factorial ( long number ) { if (number ==1 || number==0) //Base Case { return number; } else //Recursion Step { return number * factorial(number- 1); } } public static void main(String args[]) { for(int n=0;n<=100;n++) System.out.println(n + "!= " + factorial ( n )); } }

public class FactorialCalculator { public static long factorial ( long number ) { if (number ==1 || number==0) //Base Case { return number; } else //Recursion Step { return number * factorial(number- 1); } } public static void main(String args[]) { for(int n=0;n<=100;n++) System.out.println(n + "!= " + factorial ( n )); } }

Recursion Animators Factorial Reversing a String N-Queens Problem

Programming Question Using recursion: Fibonacci Series The Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, … Begins with 0 and 1: Fibonacci(0) = 0 Fibonacci(1) = 1 Each subsequent Fibonacci number is the sum of the previous two. E.g. Fibonacci(2) = 0+1 Fibonacci(3) = 1+1 Implement the tester class FinbonacciCalculator that contains the recursive method fibonacci .Call this method in main method to print fibonacci values of 0 to 40

E.g. fibonacci (3)   Recurrence Relation:

A sample run is shown:

Answer FibonacciCalculator.java public class FibonacciCalculator { public static void main(String args []) { System.out.println ("Answer="+ fibonacci (5)); } public static int fibonacci(int n) { if(n==0 || n==1) //BASE CASE return n; else return fibonacci(n-1)+ fibonacci(n-2); //RECURSIVE STEP } }

Java Stack and Heap Before we look at how recursive methods are stored and processed , lets look at two important concept in java: Java stack and heap Stack: A memory space reserved for your process by the OS the stack size is limited and is fixed and it is a LIFO data structure Mostly, the stack is used to store methods variables Each method has its own stack (a zone in the process stack), including main, which is also a function.A method stack exists only during the lifetime of that method

Java Stack and Heap Heap: A memory space managed by the OS the role of this memory is to provide additional memory resources to processes that need that supplementary space at run-time (for example, you have a simple Java application that is constructing an array with values from console); the space needed at run-time by a process is determined by functions like new

Java Memory Management The Heap and the Nursery Java objects reside in an area called  the heap .  The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full,  garbage  is collected.Performance Criteria:

jvisualvm https:// docs.oracle.com/javase/8/docs/technotes/tools/unix/jvisualvm.html

Recursion and the Method-Call Stack Let’s begin by returning to the Fibonacci example Method calls made within fibonacci (3): Method calls in program execution stack: Method stays in stack as long has not completed and returned

Programming Question Write a class Sentence that define the recursive method isPalindrome () that check whether a sentence is a palindrome or not. Palindrome: a string that is equal to itself when you reverse all characters Go hang a salami, I'm a lasagna hog Madam, I'm Adam

Hint: Remove both the first and last characters. If they are same check if remaining string is a palindrome. Case does not matter. What are the base cases/ simplest input? Strings with a single character They are palindromes The empty string It is a palindrome Find program template next slide

Class Skeleton is provided for you. Copy this code to DrJava public class Sentence { private String text; /** Constructs a sentence. @ param aText a string containing all characters of the sentence */ public Sentence(String aText) { text = aText; } /** Tests whether this sentence is a palindrome. @return true if this sentence is a palindrome, false otherwise */ public boolean isPalindrome() { //TODO – fill in } public static void main(String args[]) { Sentence p1 = new Sentence(“madam"); System.out.println (p1.isPalindrome()); Sentence p2 = new Sentence("Nope!"); System.out.println (p2.isPalindrome()); }}

Recurrence Relation   n =1, one character string, n =0, empty string

Answer public class Sentence2 { private String text; public Sentence2(String aText ) { text = aText ; } public boolean isPalindrome() { int length = text.length (); if(length<=1)//base case return true; //retrieve first and last character char first = Character.toLowerCase(text.charAt(0)); char last = Character.toLowerCase(text.charAt(length-1)); if(first==last)//first and last match { //make a shorter sentence Sentence shorter = new Sentence(text.substring (1,length-1)); //call ispalindrome on shorter sentence return shorter.isPalindrome(); } else //first and last do not match: not a palindrome { return false; } } public static void main(String args []) { Sentence2 p1 = new Sentence2("Madam"); System.out.println(p1.isPalindrome()); Sentence2 p2 = new Sentence2("Adam"); System.out.println(p2.isPalindrome()); }}Sentence2.javaContinued..

Recursion vs. Iteration Roughly speaking, recursion and iteration perform the same kinds of tasks: Solve a complicated task one piece at a time , and Combine the results . Emphasis of iteration: keep repeating until a task is “done” Emphasis of recursion: Solve a large problem by breaking it up into smaller and smaller pieces until you can solve it; combine the results .

Which is Better? No clear answer , but there are known trade-offs “ Mathematicians” often prefer recursive approach. Solutions often shorter, closer in spirit to abstract mathematical entit y. Good recursive solutions may be more difficult to design and test. “ Programmers”, esp. w/o college CS training, often prefer iterative solutions. Somehow, it seems more appealing to many . Control stays local to loop, less “magical”

Which Approach Should You Choose? Depends on the problem. The factorial example is pretty artificial; it’s so simple that it really doesn’t matter which version you choose. Many ADTs (e.g., trees) are simpler & more natural if methods are implemented recursively . Obvious and natual solution E.g. Fibonacci – recursive linear search - iterative Recursive isn’t always better: Recursive Fibonacci takes O(2 n) steps! Unusable for large n.This iterative approach is “linear” (for loop); it takes O(n) stepsMoral: “Obvious” and “natural” solutions aren’t always practical

Recursion Vs Iteraion Recursion has many negatives. Each recursive call causes another copy of the method to be created consume more memory+ processor power Since iteration occurs within a method , repeated method calls and extra memory assignment are avoided.