Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion Lecture 6 Dr. Musab.

Slides:



Advertisements
Similar presentations
Chapter 20 Recursion.
Advertisements

Starting Out with Java: From Control Structures through Objects
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 20 Recursion.
Chapter 10 Recursion Instructor: alkar/demirer. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe.
1 Recursion Overview l Introduction to recursion and recursive methods l Simple popular recursive algorithms l Writing recursive methods l Preview: Parameter.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 19 Recursion.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 14: Recursion by.
1 Introduction to Recursion  Introduction to Recursion  Example 1: Factorial  Example 2: Reversing Strings  Example 3: Fibonacci  Infinite Recursion.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L10 (Chapter 19) Recursion.
1 Recursion Overview l Introduction to recursion and recursive methods l Simple popular recursive algorithms l Writing recursive methods l Preview: 1-D.
1 Recursion Overview l Introduction to recursion and recursive methods l Simple popular recursive algorithms l Writing recursive methods l Preview: 1-D.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 14 Recursion.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved COS240 O-O Languages AUBG,
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
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.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Recursion.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Chapter 5 Loops Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.
Chapter 9 Recursion © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 23 Algorithm Efficiency.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion Chapter Nature of Recursion t Problems that lend themselves to a recursive solution have the following characteristics: –One or more.
1 Chapter 24 Developing Efficient Algorithms. 2 Executing Time Suppose two algorithms perform the same task such as search (linear search vs. binary search)
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 15 Recursion.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 13 - Recursion.
Recursion l Powerful Tool l Useful in simplifying a problem (hides details of a problem) l The ability of a function to call itself l A recursive call.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 15: Recursion Starting Out with Java: From Control Structures.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
15-1 Chapter-18: Recursive Methods –Introduction to Recursion –Solving Problems with Recursion –Examples of Recursive Methods.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 12 Recursion.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 22 Developing Efficient Algorithms.
Chapter 4 Methods F Introducing Methods –Benefits of methods, Declaring Methods, and Calling Methods F Passing Parameters –Pass by Value F Overloading.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 20 Recursion.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 15 * Recursive Algorithms.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 24 Developing Efficient Algorithms.
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.
1 Chapter 8 Recursion. 2 Objectives  To know what is a recursive function and the benefits of using recursive functions (§8.1).  To determine the base.
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,
RECURSIONL27-L28. To learn and the following concepts To design a recursive algorithm To solve problems using recursion To understand the relationship.
Chapter 9 Recursion. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.10-2 Recursive Function recursive functionThe recursive function is –a.
INF120 Basics in JAVA Programming AUBG, COS dept Lecture 07 Title: Methods, part 1 Reference: MalikFarrell, chap 1, Liang Ch 5.
Recursion Function calling itself
Chapter 18 Recursion CS1: Java Programming Colorado State University
Chapter 14 Recursion.
Chapter Topics Chapter 16 discusses the following main topics:
Topic 6 Recursion.
Chapter 15 Recursion.
Chapter 10 Recursion Instructor: Yuksel / Demirer.
Chapter 15 Recursion.
Chapter 19 Recursion.
Chapter 14: Recursion Starting Out with C++ Early Objects
Important Notes Remaining Schedule: recall the 2 bad weather days (Jan 8th, Jan 17th) we will need to make up. In providing the 2 weeks needed for the.
Chapter 14: Recursion Starting Out with C++ Early Objects
CSE 143 Lecture 11 Recursive Programming slides created by Marty Stepp
Recursion Chapter 18.
Chapter 17 Recursion.
Chapter 18 Recursion.
Week 4 Lecture-2 Chapter 6 (Methods).
Dr. Sampath Jayarathna Cal Poly Pomona
Handout-16 Recursion Overview
Chapter 3 :Recursion © 2011 Pearson Addison-Wesley. All rights reserved.
Presentation transcript:

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 18 Recursion Lecture 6 Dr. Musab Zghoul برمجة هيكلية

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 2 Motivations Suppose you want to find all the files under a directory that contains a particular word. How do you solve this problem? There are several ways to solve this problem. An intuitive solution is to use recursion by searching the files in the subdirectories recursively.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 3 Computing Factorial factorial(0) = 1; factorial(n) = n*factorial(n-1); n! = n * (n-1)! ComputeFactorial

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 4 Computing Factorial factorial(4) animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 5 Computing Factorial factorial(4) = 4 * factorial(3) animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 6 Computing Factorial factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 7 Computing Factorial factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * (2 * factorial(1)) animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 8 Computing Factorial factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * (2 * factorial(1)) = 4 * 3 * ( 2 * (1 * factorial(0))) animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 9 Computing Factorial factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * (2 * factorial(1)) = 4 * 3 * ( 2 * (1 * factorial(0))) = 4 * 3 * ( 2 * ( 1 * 1))) animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 10 Computing Factorial factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * (2 * factorial(1)) = 4 * 3 * ( 2 * (1 * factorial(0))) = 4 * 3 * ( 2 * ( 1 * 1))) = 4 * 3 * ( 2 * 1) animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 11 Computing Factorial factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * (2 * factorial(1)) = 4 * 3 * ( 2 * (1 * factorial(0))) = 4 * 3 * ( 2 * ( 1 * 1))) = 4 * 3 * ( 2 * 1) = 4 * 3 * 2 animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 12 Computing Factorial factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * (2 * factorial(1)) = 4 * 3 * ( 2 * (1 * factorial(0))) = 4 * 3 * ( 2 * ( 1 * 1))) = 4 * 3 * ( 2 * 1) = 4 * 3 * 2 = 4 * 6 animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 13 Computing Factorial factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * (2 * factorial(1)) = 4 * 3 * ( 2 * (1 * factorial(0))) = 4 * 3 * ( 2 * ( 1 * 1))) = 4 * 3 * ( 2 * 1) = 4 * 3 * 2 = 4 * 6 = 24 animation factorial(0) = 1; factorial(n) = n*factorial(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 14 Trace Recursive factorial animation Executes factorial(4)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 15 Trace Recursive factorial animation Executes factorial(3)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 16 Trace Recursive factorial animation Executes factorial(2)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 17 Trace Recursive factorial animation Executes factorial(1)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 18 Trace Recursive factorial animation Executes factorial(0)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 19 Trace Recursive factorial animation returns 1

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 20 Trace Recursive factorial animation returns factorial(0)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 21 Trace Recursive factorial animation returns factorial(1)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 22 Trace Recursive factorial animation returns factorial(2)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 23 Trace Recursive factorial animation returns factorial(3)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 24 Trace Recursive factorial animation returns factorial(4)

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 25 factorial(4) Stack Trace

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 26 Other Examples f(0) = 0; f(n) = n + f(n-1);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 import java.util.Scanner; 2 3 public class ComputeFactorial { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Create a Scanner 7 Scanner input = new Scanner(System.in); 8 System.out.print("Enter a non-negative integer: "); 9 int n = input.nextInt(); // Display factorial 12 System.out.println("Factorial of " + n + " is " + factorial(n)); 13 } /** Return the factorial for a specified number */ 16 public static long factorial(int n) { 17 if (n == 0) // Base case 18 return 1; 19 else 20 return n * factorial(n - 1); // Recursive call 21 } 22 } 27

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 28 Fibonacci Numbers Fibonacci series: … indices: fib(0) = 0; fib(1) = 1; fib(index) = fib(index -1) + fib(index -2); index >=2 fib(3) = fib(2) + fib(1) = (fib(1) + fib(0)) + fib(1) = (1 + 0) +fib(1) = 1 + fib(1) = = 2 ComputeFibonacci

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved import java.util.Scanner; 2 3 public class ComputeFibonacci { 4 /** Main method */ 5 public static void main(String[] args) { 6 // Create a Scanner 7 Scanner input = new Scanner(System.in); 8 System.out.print("Enter an index for a Fibonacci number: "); 9 int index = input.nextInt(); // Find and display the Fibonacci number 12 System.out.println("The Fibonacci number at index " 13 + index + " is " + fib(index)); 14 } 15

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved /** The method for finding the Fibonacci number */ 17 public static long fib(long index) { 18 if (index == 0) // Base case 19 return 0; 20 else if (index == 1) // Base case 21 return 1; 22 else // Reduction and recursive calls 23 return fib(index - 1) + fib(index - 2); 24 } 25 }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 31 Fibonnaci Numbers, cont.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 32 Characteristics of Recursion All recursive methods have the following characteristics: –One or more base cases (the simplest case) are used to stop recursion. –Every recursive call reduces the original problem, bringing it increasingly closer to a base case until it becomes that case. In general, to solve a problem using recursion, you break it into subproblems. If a subproblem resembles the original problem, you can apply the same approach to solve the subproblem recursively. This subproblem is almost the same as the original problem in nature with a smaller size.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 33 Problem Solving Using Recursion Let us consider a simple problem of printing a message for n times. You can break the problem into two subproblems: one is to print the message one time and the other is to print the message for n-1 times. The second problem is the same as the original problem with a smaller size. The base case for the problem is n==0. You can solve this problem using recursion as follows: nPrintln(“Welcome“, 5); public static void nPrintln(String message, int times) { if (times >= 1) { System.out.println(message); nPrintln(message, times - 1); } // The base case is times == 0 }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 34 Think Recursively Many of the problems presented in the early chapters can be solved using recursion if you think recursively. For example, the palindrome problem can be solved recursively as follows: public static boolean isPalindrome(String s) { if (s.length() <= 1) // Base case return true; else if (s.charAt(0) != s.charAt(s.length() - 1)) // Base case return false; else return isPalindrome(s.substring(1, s.length() - 1)); }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 35 Recursive Helper Methods The preceding recursive isPalindrome method is not efficient, because it creates a new string for every recursive call. To avoid creating new strings, use a helper method: public static boolean isPalindrome(String s) { return isPalindrome(s, 0, s.length() - 1); } public static boolean isPalindrome(String s, int low, int high) { if (high <= low) // Base case return true; else if (s.charAt(low) != s.charAt(high)) // Base case return false; else return isPalindrome(s, low + 1, high - 1); }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 36 Recursive Selection Sort 1. Find the smallest number in the list and swaps it with the first number. 2. Ignore the first number and sort the remaining smaller list recursively.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved public class RecursiveSelectionSort { 2 public static void sort(double[] list) { 3 sort(list, 0, list.length - 1); // Sort the entire list 4 } 5 6 private static void sort(double[] list, int low, int high) { 7 if (low < high) { 8 // Find the smallest number and its index in list(low.. high) 9 int indexOfMin = low; 10 double min = list[low]; 11 for (int i = low + 1; i <= high; i++) { 12 if (list[i] < min) { 13 min = list[i]; 14 indexOfMin = i; 15 } 16 }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved // Swap the smallest in list(low.. high) with list(low) 19 list[indexOfMin] = list[low]; 20 list[low] = min; // Sort the remaining list(low+1.. high) 23 sort(list, low + 1, high); 24 } 25 } public static void main(String[] args) { 28 double[] list = {2, 1, 3, 1, 2, 5, 2, -1, 0}; 29 sort(list); 30 for (int i = 0; i < list.length; i++) 31 System.out.print(list[i] + " "); 32 } 33 }

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 39 Tower of Hanoi  There are n disks labeled 1, 2, 3,..., n, and three towers labeled A, B, and C.  No disk can be on top of a smaller disk at any time.  All the disks are initially placed on tower A.  Only one disk can be moved at a time, and it must be the top disk on the tower.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 40 Tower of Hanoi, cont.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 41 Solution to Tower of Hanoi The Tower of Hanoi problem can be decomposed into three subproblems.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 42 Solution to Tower of Hanoi  Move the first n - 1 disks from A to C with the assistance of tower B.  Move disk n from A to B.  Move n - 1 disks from C to B with the assistance of tower A. TowerOfHanoi

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 43 Exercise 18.3 GCD gcd(2, 3) = 1 gcd(2, 10) = 2 gcd(25, 35) = 5 gcd(205, 301) = 5 gcd(m, n) Approach 1: Brute-force, start from min(n, m) down to 1, to check if a number is common divisor for both m and n, if so, it is the greatest common divisor. Approach 2: Euclid’s algorithm Approach 3: Recursive method

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 44 Approach 2: Euclid’s algorithm // Get absolute value of m and n; t1 = Math.abs(m); t2 = Math.abs(n); // r is the remainder of t1 divided by t2; r = t1 % t2; while (r != 0) { t1 = t2; t2 = r; r = t1 % t2; } // When r is 0, t2 is the greatest common // divisor between t1 and t2 return t2;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 45 Approach 3: Recursive Method gcd(m, n) = n if m % n = 0; gcd(m, n) = gcd(n, m % n); otherwise;

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 46 Recursion vs. Iteration Recursion is an alternative form of program control. It is essentially repetition without a loop. Recursion bears substantial overhead. Each time the program calls a method, the system must assign space for all of the method’s local variables and parameters. This can consume considerable memory and requires extra time to manage the additional space.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 47 Advantages of Using Recursion Recursion is good for solving the problems that are inherently recursive.