Recursion For some problems, it’s useful to have a method call itself.

Slides:



Advertisements
Similar presentations
Recursion Chapter 14. Overview Base case and general case of recursion. A recursion is a method that calls itself. That simplifies the problem. The simpler.
Advertisements

Recursion CS 367 – Introduction to Data Structures.
Recursion vs. Iteration The original Lisp language was truly a functional language: –Everything was expressed as functions –No local variables –No iteration.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 13 – Recursion.
Chapter 18 Recursion "To iterate is human, to recurse divine.", L. Peter Deutsch.
Factorial Recursion stack Binary Search Towers of Hanoi
CHAPTER 13 Recursion. Recursive Solution A recursive solution  solves a problem by solving a smaller instance of the problem. Example  How do we go.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Computer Science II Recursion Professor: Evan Korth New York University.
Fundamentals of Computer Science Lecture 14: Recursion Instructor: Evan Korth New York University.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
1 CSCD 300 Data Structures Recursion. 2 Proof by Induction Introduction only - topic will be covered in detail in CS 320 Prove: N   i = N ( N + 1.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Unit 7 1 Unit 7: Recursion H Recursion is a fundamental programming technique that can provide an elegant solution to a certain kinds of problems H In.
Unit 181 Recursion Definition Recursive Methods Constructing Recursion Benefits and Usage Infinite Recursion Recursion Removal Examples Exercises.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
Programming in C++ Language ( ) Lecture 6: Functions-Part2 Dr. Lubna Badri.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
Functions and an Introduction to Recursion.  Recursive function ◦ A function that calls itself, either directly, or indirectly (through another function)
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
AP Computer Science Instructor Alabama School of Fine Arts
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion Lecture 6 Dr. Musab.
1 Recursion n what is it? n how to build recursive algorithms n recursion analysis n tracing simple recursive functions n hands on attempts at writing.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
1 CSC 143 Recursion [Reading: Chapter 17]. 2 Recursion  A recursive definition is one which is defined in terms of itself.  Example:  Sum of the first.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Recursion Powerful Tool
Recursion.
Recursion Version 1.0.
Recursion The programs discussed so far have been structured as functions that invoke one another in a disciplined manner For some problems it is useful.
Recursion what is it? how to build recursive algorithms
Chapter 15 Recursion.
Introduction to Recursion
Introduction to Recursion
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Recursion A problem solving technique where an algorithm is defined in terms of itself A recursive method is a method that calls itself A recursive algorithm.
RECURSION.
Chapter 17 Recursion.
Chapter 15 Recursion.
Java 4/4/2017 Recursion.
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
6.11 Function Call Stack and Activation Records
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Ch 12 Recursion Mr. Dave Clausen La Cañada High School
MSIS 655 Advanced Business Applications Programming
Stacks & Recursion.
Recursion Data Structures.
Recursion.
Recursion Chapter 18.
Chapter 17 Recursion.
Chapter 17 Recursion.
Chapter 18 Recursion.
Recursion Taken from notes by Dr. Neil Moore
Lecture 12 Recursion part 1 CSE /26/2018.
Chapter 18 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Programming Fundamentals Lecture #7 Functions
Recursive Thinking.
Ch 12 Recursion Mr. Dave Clausen La Cañada High School
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. Fibonacci method Factorial method Towers of Hanoi Merge sort Linear search Binary search Quick sort

Q: how to write a recursive method to add numbers from 0 to n? Public int add(n) public class TestRecursion2 { public static void main(String args[]) System.out.println("answer="+add(3)); } public static int add(int n) if(n<=0)//base case return 0; else System.out.println(n +" + "); return n+ add(n-1); //general case

Q: How do you modify code to add range of values from n1(start) to n2(end)? public class TestRecursion3 { public static void main(String args[]) System.out.println("answer add2(0,3)="+add2(0,3)); } public static int add2(int first, int last) if(last<=0)//base case return 0; else return last+ add(first, last-1); //general case

Q: Can you think of a different recursive implementation for previous? public class TestRecursion3 { public static void main(String args[]) System.out.println("answer add3(0,10)="+add3(0,10)); } public static int add3(int first, int last) //add numbers in range first to last (first and last inclusive) different recursive implementation if(first==last) return first; if(last-first==1) return first+last; return add3(first, first+(last-first)/2)+add3((first+(last-first)/2)+1,last); //add3(first, last/2) + add(last/2+1,last) is wrong. Last/2 can be less than first

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. 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. return add3(first, first+(last-first)/2)+add3((first+(last-first)/2)+1,last); Add(0,10) Add(0,5) + add(6,10) Add(0,2) + Add(3,5) + add(6,8) + add(9,10) Add(0,1)+add(2,2) +add(3,4) + add(5,5) + add(6,7) + add(8,8)

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.

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 long factorial (long n) long factorial = n; for(int i=(int)n;i>=1;i--) factorial *= i; return factorial; } public static void main(String args[]) for(int n=0;n<=100;n++) System.out.println(n+"!= +factorial (n)); If everything is int (including factorial), after 12! You get weird results! If everything is long (including factorial), after 21! You get weird results!

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.

Answer Recursive method: public static long factorial(long number) { if (number ==1 || number==0) //Base Case return number; } else //Recursion Step return number * factorial(number-1);

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)

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) return n; else return fibonacci(n-1)+fibonacci(n-2);

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 determined in the compiler phase based on variables declaration and other compiler options 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 (remember, it the same function used to create objects in Java) which are used to get additional space in Heap.

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: When the first method call (A) is made, an activation record containing the value of the local variable number (3, in this case) is pushed onto the program-execution stack. This stack, including the activation record for method call A, is illustrated in part (a) Within method call A, method calls B and E are made. The original method call has not yet completed, so its activation record remains on the stack. The first method call to be made from within A is method call B, so the activation record for method call B is pushed onto the stack on top of the one for method call A. Method call B must execute and complete before method call E is made. Within method call B, method calls C and D will be made. Method call C is made first, and its activation record is pushed onto the stack When method call C executes, it makes no further method calls, but simply returns the value 1. When this method returns, its activation record is popped Method stays in stack as long has not completed and returned

Homework: 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

You need to shorten the string to keep only letters. Hint: Remove both the first and last characters. If they are same check if remaining string is a palindrome. You need to shorten the string to keep only letters. 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

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, I'm Adam."); System.out.println(p1.isPalindrome()); Sentence p2 = new Sentence("Nope!"); System.out.println(p2.isPalindrome());

Answer Sentence.java Continued.. 1 public class Sentence { 2 3 private String text; 4 5 public Sentence(String aText) { 6 text = aText; 7 } 8 9 public boolean isPalindrome() { 10 int length = text.length(); 11 12 if (length <= 1) { return true; } //BASE CASE 13 14 char first = Character.toLowerCase(text.charAt(0)); 15 char last = Character.toLowerCase(text.charAt(length - 1)); 16 17 if (Character.isLetter(first) && Character.isLetter(last)) { 18 if (first == last) { 19 Sentence shorter = new Sentence(text.substring(1, length - 1)); 20 return shorter.isPalindrome(); 21 } 22 else { 23 return false; 24 } 25 } 26 else if (!Character.isLetter(last)) { 27 Sentence shorter = new Sentence(text.substring(0, length - 1)); 28 return shorter.isPalindrome(); 29 } 30 else { 31 Sentence shorter = new Sentence(text.substring(1)); 32 return shorter.isPalindrome(); 33 } 34 } Continued..

Answer 36 public static void main(String[] args) { 37 Sentence p1 = new Sentence("Madam, I'm Adam."); 38 System.out.println(p1.isPalindrome()); 39 Sentence p2 = new Sentence("Nope!"); 40 System.out.println(p2.isPalindrome()); 41 Sentence p3 = new Sentence("dad"); 42 System.out.println(p3.isPalindrome()); 43 Sentence p4 = new Sentence("Go hang a salami, I'm a lasagna hog."); 44 System.out.println(p4.isPalindrome()); 45 } 46}

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 entity. 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. Recursive isn’t always better: Recursive Fibonacci takes O(2n) steps! Unusable for large n. This iterative approach is “linear” (for loop); it takes O(n) steps Moral: “Obvious” and “natural” solutions aren’t always practical Recursive: F(4) = f(3) + f(2) = f(2) + f( 1) + f(1) + f(0) = f(1) + f(0) 0 1 0 1 0 Iterative: static int fibIteration(int n) { int x = 0, y = 1, z = 1; for (int i = 0; i < n; i++) { x = y; y = z; z = x + y; } return x;

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.