Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - 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.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 13 – Recursion.
Recursion - see Recursion. RHS – SOC 2 Recursion We know that: –We can define classes –We can define methods on classes –Mehtods can call other methods.
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.
Recursive methods. Recursion A recursive method is a method that contains a call to itself Often used as an alternative to iteration when iteration is.
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.
Scott Grissom, copyright 2004 Chapter 5 Slide 1 Analysis of Algorithms (Ch 5) Chapter 5 focuses on: algorithm analysis searching algorithms sorting algorithms.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
CHAPTER 17 RECURSION CHAPTER GOALS –To learn about the method of recursion –To understand the relationship between recursion and iteration –To analysis.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Recursion Chapter 7. Chapter 7: Recursion2 Chapter Objectives To understand how to think recursively To learn how to trace a recursive method To learn.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Recursion.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 19: 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.
C++ for Everyone by Cay Horstmann Copyright © 2012 by John Wiley & Sons. All rights reserved Chapter Eleven: Recursion Slides by Evan Gallagher.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
Chapter 13 Recursion. Topics Simple Recursion Recursion with a Return Value Recursion with Two Base Cases Binary Search Revisited Animation Using Recursion.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
Recursion Chapter 7. Chapter Objectives  To understand how to think recursively  To learn how to trace a recursive method  To learn how to write recursive.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Functions and an Introduction to Recursion.  Recursive function ◦ A function that calls itself, either directly, or indirectly (through another function)
Chapter 12 Recursion, Complexity, and Searching and Sorting
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.
AP Computer Science Instructor Alabama School of Fine Arts
Chapter 8 Recursion Modified.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Thirteen: Recursion.
CHAPTER 17 RECURSION. CHAPTER GOALS To learn about the method of recursion To understand the relationship between recursion and iteration To analysis.
Chapter 18 Recursion. Chapter Goals To learn about the method of recursion To understand the relationship between recursion and iteration To analyze problems.
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.
Copyright © 2013 by John Wiley & Sons. All rights reserved. RECURSION CHAPTER Slides by Rick Giles 13.
ICOM 4015: Advanced Programming Lecture 13 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Thirteen:
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 15 Recursion.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
Java How to Program, 10/e Late Objects Version © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Maitrayee Mukerji. Factorial For any positive integer n, its factorial is n! is: n! = 1 * 2 * 3 * 4* ….* (n-1) * n 0! = 1 1 ! = 1 2! = 1 * 2 = 2 5! =
CS 116 Object Oriented Programming II Lecture 13 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
Chapter 6 (Lafore’s Book) Recursion Hwajung Lee.  Definition: An algorithmic technique. To solve a problem on an instance of size n, the instance is:
Copyright © 2013 by John Wiley & Sons. All rights reserved. RECURSION CHAPTER 11 May 27, 2013 Slides by James Tam Department of Computer Science, University.
Recursion Version 1.0.
Chapter 13 Recursion.
Topic 6 Recursion.
RECURSION.
Department of Computer Science,
Data Structures Recursion CIS265/506: Chapter 06 - Recursion.
Java Software Structures: John Lewis & Joseph Chase
Recursion For some problems, it’s useful to have a method call itself.
Advanced Java Programming
Recursion Chapter 18.
Chapter 13 – Recursion Big Java by Cay Horstmann
Chapter 18 Recursion.
Programming Fundamentals Lecture #7 Functions
Presentation transcript:

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.2 Chapter Goals  To learn to “think recursively”  To be able to use recursive helper methods  To understand the relationship between recursion and iteration  To understand when the use of recursion affects the efficiency of an algorithm  To analyze problems that are much easier to solve by recursion than by iteration  To process data with recursive structures using mutual recursion

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

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

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.7 Programming Question  Write a iterative (non-recursive) method factorialIterrative 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.8 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 factorialIterative(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+"!= "+factorialIterative(n)); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.9 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.10 Programming Question  Modify FactorialCalculator to add a recursive factorial method.

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.12 public class FactorialCalculator { public static long factorialIterative(int n) { int factorial = n; for(int i=(int)n;i>=1;i--) factorial *= i; return factorial; } public static long factorialRecursive(long number) { if (number ==1 || number==0) //Base Case { return number; } else //Recursion Step { return number * factorialRecursive(number-1); } public static void main(String args[]) { for(int n=0;n<=100;n++) System.out.println(n+"!= "+factorialRecursive(n)); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.13 Programming Question  Since factorial values tend to be large, using BigInteger rather than long as data type is more appropriate.  Modify FactorialCalculator to use BigInteger data type rather than long (modify recursive version only).

Copyright © 2014 by John Wiley & Sons. All rights reserved.14  Since factorial values tend to be large, using BigInteger rather than long as data type is more appropriate: import java.math.BigInteger; public class FactorialCalculator { public static BigInteger factorialRecursive(BigInteger number) { if (number.compareTo(BigInteger.ONE)==0 || number.compareTo(BigInteger.ZERO)==0) //Base Case { return number; } else //Recursion Step { return number.multiply(factorialRecursive(number.subtract(BigInteger.ONE))); } public static void main(String args[]) { for(int n=0;n<=100;n++) System.out.println(n+"!= "+factorialRecursive(BigInteger.valueOf(n))); }

Copyright © 2014 by John Wiley & Sons. All rights reserved.15  Output:

Copyright © 2014 by John Wiley & Sons. All rights reserved.16 Programming Question  Using recursion: Fibonacci Series The Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, … Begins with 0 and 1 Each subsequent Fibonacci number is the sum of the previous two.  Implement the tester class FinbonacciCalculator that contains the recursive method fibonacci. Hint: Use BigInteger as return data type Call this method in main method to print fibonacci values of 0 to 40:

Copyright © 2014 by John Wiley & Sons. All rights reserved.17  E.g. fibonacci(3)

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.19 Answer FibonacciCalculator.java

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

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.22 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.23 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.24 Class Skeleton is provided for you. Add a main method that create several sentences and print if they are palindromes. 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() {... } public static void main(String args[]) { }

Copyright © 2014 by John Wiley & Sons. All rights reserved.25 Hint:  Remove both the first and last characters.  If they are same check if remaining string is a palindrome.  What are the base cases/ simplest input? Strings with a single character They are palindromes The empty string It is a palindrome

Copyright © 2014 by John Wiley & Sons. All rights reserved.26 Answer 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(); if (length <= 1) { return true; } //BASE CASE char first = Character.toLowerCase(text.charAt(0)); 15 char last = Character.toLowerCase(text.charAt(length - 1)); 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 } Sentence.java Continued..

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

Copyright © 2014 by John Wiley & Sons. All rights reserved.28 Recursion Vs Iteraion  Recursion has many negatives. It repeatedly invokes the mechanism, and consequently the overhead, of method calls. This repetition can be expensive in terms of both processor time and memory space. Each recursive call causes another copy of the method to be created this set of copies can consume considerable memory space. Since iteration occurs within a method, repeated method calls and extra memory assignment are avoided.

Copyright © 2014 by John Wiley & Sons. All rights reserved.29 Question Answer: No, the recursive solution is about as efficient as the iterative approach. Both require n – 1 multiplications to compute n!. You can compute the factorial function either with a loop, using the definition that n! = 1 × 2 ×... × n, or recursively, using the definition that 0! = 1and n! = (n – 1)! × n. Is the recursive approach inefficient in this case?

Copyright © 2014 by John Wiley & Sons. All rights reserved.30 Question Answer: The recursive algorithm performs about as well as the loop. Unlike the recursive Fibonacci algorithm, this algorithm doesn’t call itself again on the same input. For example, the sum of the array is computed as the sum of and , then as the sums of 1 4, 9 16, 25 36, and 49 64, which can be computed directly. To compute the sum of the values in an array, you can split the array in the middle, recursively compute the sums of the halves, and add the results. Compare the performance of this algorithm with that of a loop that adds the values.

Copyright © 2014 by John Wiley & Sons. All rights reserved.31 Programming Question  Permutations  Using recursion, you can find all arrangements of a set of objects.  A permutation is a rearrangement of the letters.

Copyright © 2014 by John Wiley & Sons. All rights reserved.32 Programming Question  E.g. Permutations The string "eat" has six permutations: "eat" "eta" "aet" "ate" "tea" "tae” Design a class Permutations that contains a recursive method permutations that takes a string and return a list of permutations public static ArrayList permutations(String word) In main method call this method to print all permutations possible.

Copyright © 2014 by John Wiley & Sons. All rights reserved.33  Problem: Generate all the permutations of "eat". First generate all permutations that start with the letter 'e', then 'a' then 't'.  How do we generate the permutations that start with 'e'? We need to know the permutations of the substring "at". But that’s the same problem —to generate all permutations— with a simpler input Prepend the letter 'e' to all the permutations you found of 'at'. Do the same for 'a' and 't'.  Provide a special case for the simplest strings. The simplest string is the empty string, which has a single permutation—itself.

Copyright © 2014 by John Wiley & Sons. All rights reserved.34 Answer 1 import java.util.ArrayList; 2 3 /** 4 This program computes permutations of a string. 5 */ 6 public class Permutations 7 { 8 public static void main(String[] args) 9 { 10 for (String s : permutations("eat")) 11 { 12 System.out.println(s); 13 } 14 } /** 17 Gets all permutations of a given word. word the string to permute a list of all permutations 20 */ 21 public static ArrayList permutations(String word) 22 { 23 ArrayList result = new ArrayList (); 24 Continued Permutations.java

Copyright © 2014 by John Wiley & Sons. All rights reserved // The empty string has a single permutation: itself 26 if (word.length() == 0) 27 { 28 result.add(word); 29 return result; 30 } 31 else 32 { 33 // Loop through all character positions 34 for (int i = 0; i < word.length(); i++) 35 { 36 // Form a shorter word by removing the ith character 37 String shorter = word.substring(0, i) + word.substring(i + 1); // Generate all permutations of the simpler word 40 ArrayList shorterPermutations = permutations(shorter); // Add the removed character to the front of 43 // each permutation of the simpler word, 44 for (String s : shorterPermutations) 45 { 46 result.add(word.charAt(i) + s); 47 } 48 } 49 // Return all permutations 50 return result; 51 } 52 } 53 } 54 Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved.36 Program Run: eat eta aet ate tea tae

Copyright © 2014 by John Wiley & Sons. All rights reserved.37 References  Java How to Program, Dietel and Dietel  8-understand-stack-and-heap/ 8-understand-stack-and-heap/