Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion.

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

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.
Recursion. Recursive Definitions A recursive definition is one which uses the word being defined in the definition Not always useful:  for example, in.
Lesson 19 Recursion CS1 -- John Cole1. Recursion 1. (n) The act of cursing again. 2. see recursion 3. The concept of functions which can call themselves.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 19 Recursion.
Recursion. Binary search example postponed to end of lecture.
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.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
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.
29-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
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.
CHAPTER 10 Recursion. 2 Recursive Thinking Recursion is a programming technique in which a method can call itself to solve a problem A recursive definition.
Unit 181 Recursion Definition Recursive Methods Constructing Recursion Benefits and Usage Infinite Recursion Recursion Removal Examples Exercises.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Recursion.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion.
CS Discrete Mathematical Structures Mehdi Ghayoumi MSB rm 132 Ofc hr: Thur, 9:30-11:30a.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: Recursion.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
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++
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Chapter 15 Recursion.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Functions and an Introduction to Recursion.  Recursive function ◦ A function that calls itself, either directly, or indirectly (through another function)
Recursion Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 19 : Recursion King Fahd University of Petroleum & Minerals College of Computer.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
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.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
CS212: DATASTRUCTURES Lecture 3: Recursion 1. Lecture Contents 2  The Concept of Recursion  Why recursion?  Factorial – A case study  Content of a.
Recursion Recursion Chapter 12. Outline n What is recursion n Recursive algorithms with simple variables n Recursion and the run-time stack n Recursion.
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.
 Prentice Hall. All rights reserved. 1 Recursion (Section 7.13 & Exercise7.40 from ed.3) (Sections 6.15, 6.16 from ed.1) Many slides modified.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 15 Recursion.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Data Structures I (CPCS-204) Week # 5: Recursion Dr. Omar Batarfi Dr. Yahya Dahab Dr. Imtiaz Khan.
CSC 143 P 1 CSC 143 Recursion [Chapter 5]. CSC 143 P 2 Recursion  A recursive definition is one which is defined in terms of itself  Example:  Compound.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Chapter 18 Recursion CS1: Java Programming Colorado State University
Recursion Version 1.0.
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.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Recursion For some problems, it’s useful to have a method call itself.
Recursion Chapter 18.
Chapter 17 Recursion.
Chapter 18 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Programming Fundamentals Lecture #7 Functions
Presentation transcript:

Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion

Copyright © 2014 by John Wiley & Sons. All rights reserved.2 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.

Copyright © 2014 by John Wiley & Sons. All rights reserved.3  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

Copyright © 2014 by John Wiley & Sons. All rights reserved.4  Q: how to write a recursive method to add numbers from 0 to n? Public int add(n)

Copyright © 2014 by John Wiley & Sons. All rights reserved.5  Q: How do you modify code to add range of values from n1(start) to n2(end)?

Copyright © 2014 by John Wiley & Sons. All rights reserved.6  Q: Can you think of a different recursive implementation for previous?

Copyright © 2014 by John Wiley & Sons. All rights reserved.7 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.

Copyright © 2014 by John Wiley & Sons. All rights reserved.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.

Copyright © 2014 by John Wiley & Sons. All rights reserved.9 Recurrence Relations Sum(s, f) Add2 Add3 Power(b, e) b e = b.b e-1 b e = b e/2.b e/2

Copyright © 2014 by John Wiley & Sons. All rights reserved.10 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! = = 120 4! = = 24

Copyright © 2014 by John Wiley & Sons. All rights reserved.11 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:

Copyright © 2014 by John Wiley & Sons. All rights reserved.12 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)); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.13 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; }

Copyright © 2014 by John Wiley & Sons. All rights reserved.14 How to write it recursively? Recursive aspect comes from : n! = n.(n-1)! E.g. 5!

Copyright © 2014 by John Wiley & Sons. All rights reserved.15 Programming Question  Modify FactorialCalculator factorial method to have a recursive implementation. Recurrence Relation:

Copyright © 2014 by John Wiley & Sons. All rights reserved.16 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)); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.17 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)); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.18  Recursion Animators Factorial Reversing a String N-Queens Problem

Copyright © 2014 by John Wiley & Sons. All rights reserved.19 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

Copyright © 2014 by John Wiley & Sons. All rights reserved.20  E.g. fibonacci(3) Recurrence Relation:

Copyright © 2014 by John Wiley & Sons. All rights reserved.21  A sample run is shown:

Copyright © 2014 by John Wiley & Sons. All rights reserved.22 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 }

Copyright © 2014 by John Wiley & Sons. All rights reserved.23 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

Copyright © 2014 by John Wiley & Sons. All rights reserved.24 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

Copyright © 2014 by John Wiley & Sons. All rights reserved.25 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:

Copyright © 2014 by John Wiley & Sons. All rights reserved.26 jvisualvm

Copyright © 2014 by John Wiley & Sons. All rights reserved.27 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

Copyright © 2014 by John Wiley & Sons. All rights reserved.28 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

Copyright © 2014 by John Wiley & Sons. All rights reserved.29 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

Copyright © 2014 by John Wiley & Sons. All rights reserved.30 Class Skeleton is provided for you. Copy this code to DrJava public class Sentence { private String text; /** Constructs a aText a string containing all characters of the sentence */ public Sentence(String aText) { text = aText; } /** Tests whether this sentence is a 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()); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.31 Recurrence Relation n=1, one character string, n=0, empty string

Copyright © 2014 by John Wiley & Sons. All rights reserved.32 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.java Continued..

Copyright © 2014 by John Wiley & Sons. All rights reserved.33 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.

Copyright © 2014 by John Wiley & Sons. All rights reserved.34 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”

Copyright © 2014 by John Wiley & Sons. All rights reserved.35 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) steps  Moral: “Obvious” and “natural” solutions aren’t always practical

Copyright © 2014 by John Wiley & Sons. All rights reserved.36 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.