Review of Recursion What is a Recursive Method?

Slides:



Advertisements
Similar presentations
3/25/2017 Chapter 16 Recursion.
Advertisements

Recursion Outline of the upcoming lectures: Review of Recursion
Factorial Recursion stack Binary Search Towers of Hanoi
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.
Analysis of Recursive Algorithms What is a recurrence relation? Forming Recurrence Relations Solving Recurrence Relations Analysis Of Recursive Factorial.
Analysis of Recursive Algorithms What is a recurrence relation? Forming Recurrence Relations Solving Recurrence Relations Analysis Of Recursive Factorial.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. ETC - 1 What comes next? Recursion (Chapter 15) Recursive Data Structures.
Recursion … just in case you didn’t love loops enough …
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.
Recursion. 2 CMPS 12B, UC Santa Cruz Solving problems by recursion How can you solve a complex problem? Devise a complex solution Break the complex problem.
Lecture 8 Analysis of Recursive Algorithms King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer.
Recursion Outline of the upcoming lectures: –Review of Recursion –Types of Recursive Methods –Final Remarks on Recursion.
Analysis of Recursive Algorithms What is a recurrence relation? Forming Recurrence Relations Solving Recurrence Relations Analysis Of Recursive Factorial.
Review of Recursion What is a Recursive Method? The need for Auxiliary (or Helper) Methods How Recursive Methods work Tracing of Recursive Methods.
Department of Computer Engineering Recursive Problem Solving Computer Programming for International Engineers.
Analysis of Algorithm Lecture 3 Recurrence, control structure and few examples (Part 1) Huma Ayub (Assistant Professor) Department of Software Engineering.
Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
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.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 8 Recursion Modified.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Recursion Chapter What is recursion? Recursion occurs when a method calls itself, either directly or indirectly. Used to solve difficult, repetitive.
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.
Lecture 11 Recursion. A recursive function is a function that calls itself either directly, or indirectly through another function; it is an alternative.
Recursion Chapter 10 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion.
Recursion You may have seen mathematical functions defined using recursion Factorial(x) = 1 if x
Recursion Powerful Tool
Programming with Recursion
Recursion.
Review of Recursion What is a Recursive Method?
CS212: Data Structures and Algorithms
Unit 6 Analysis of Recursive Algorithms
Recursion CENG 707.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 19: Recursion.
Recursion CENG 707.
Analysis of Recursive Algorithms
Chapter 15 Recursion.
Recursion: The Mirrors
Unit 5 Recursion King Fahd University of Petroleum & Minerals
Chapter 15 Recursion.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Programming: Program Design Including Data Structures
Java Software Structures: John Lewis & Joseph Chase
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursive Definitions
Chapter 12 Recursion (methods calling themselves)
Recursion Chapter 11.
Chapter 14: Recursion Starting Out with C++ Early Objects
CS1120: Recursion.
Recursion Data Structures.
Recursion.
7.Recursion Recursion is the name given for expression anything in terms of itself. Recursive function is a function which calls itself until a particular.
Review of Recursion What is a Recursive Method?
CS302 - Data Structures using C++
CSC 143 Recursion.
Review of Recursion What is a Recursive Method?
Chapter 18 Recursion.
Dr. Sampath Jayarathna Cal Poly Pomona
Analysis of Recursive Algorithms
Chapter 3 Recursion.
ICS103 Programming in C Lecture 11: Recursive Functions
Recursion Chapter 12.
Recursive Thinking.
Analysis of Recursive Algorithms
Presentation transcript:

Review of Recursion What is a Recursive Method? The need for Auxiliary (or Helper) Methods How Recursive Methods work Tracing of Recursive Methods

What is a Recursive Method? A method is recursive if it calls itself either directly or indirectly. Recursion is a technique that allows us to break down a problem into one or more simpler sub-problems that are similar in form to the original problem. Example 1: A recursive method for computing x! This method illustrates all the important ideas of recursion: A base (or stopping) case Code first tests for stopping condition ( is x = = 0 ?) Provides a direct (non-recursive) solution for the base case (0! = 1). The recursive case Expresses solution to problem in 2 (or more) smaller parts Invokes itself to compute the smaller parts, eventually reaching the base case long factorial (int x) { if (x == 0) return 1; //base case else return x * factorial (x – 1); //recursive case }

What is a Recursive Method? Example 2: count zeros in an array int countZeros(int[] x, int index) { if (index == 0) return x[0] == 0 ? 1: 0; else if (x[index] == 0) return 1 + countZeros(x, index – 1); else return countZeros(x, index – 1); }

The need for Auxiliary (or Helper) Methods Auxiliary or helper methods are used for one or more of the following reasons: To make recursive methods more efficient. To make the user interface to a method simpler by hiding the method's initializations. Example 1: Consider the method: The condition x < 0 which should be executed only once is executed in each recursive call. We can use a private auxiliary method to avoid this: public long factorial (int x){ if (x < 0) throw new IllegalArgumentException("Negative argument"); else if (x == 0) return 1; else return x * factorial(x – 1); }

The need for Auxiliary (or Helper) Methods public long factorial(int x){ if (x < 0) throw new IllegalArgumentException("Negative argument"); else return factorialAuxiliary(x); } private long factorialAuxiliary(int x){ if (x == 0) return 1; return x * factorialAuxiliary(x – 1);

The need for Auxiliary (or Helper) Methods Example 2: Consider the method: The first time the method is called, the parameter low and high must be set to 0 and array.length – 1 respectively. Example: From a user's perspective, the parameters low and high introduce an unnecessary complexity that can be avoided by using an auxiliary method: public int binarySearch(int target, int[] array, int low, int high) { if(low > high) return -1; else { int middle = (low + high)/2; if(array[middle] == target) return middle; else if(array[middle] < target) return binarySearch(target, array, middle + 1, high); else return binarySearch(target, array, low, middle - 1); } int result = binarySearch (target, array, 0, array.length -1);

The need for Auxiliary (or Helper) Methods A call to the method becomes simple: public int binarySearch(int target, int[] array){ return binarySearch(target, array, 0, array.length - 1); } private int binarySearch(int target, int[] array, int low, int high){ if(low > high) return -1; else{ int middle = (low + high)/2; if(array[middle] == target) return middle; else if(array[middle] < target) return binarySearch(target, array, middle + 1, high); else return binarySearch(target, array, low, middle - 1); int result = binarySearch(target, array);

The need for Auxiliary (or Helper) Methods Example 3: Consider the following method that returns the length of a MyLinkedList instance: The method must be invoked by a call of the form: By using an auxiliary method, we can simplify the call to: public int length(Element element){ if(element == null) return 0; else return 1 + length(element.next); } list.length(list.getHead()); list.length();

The need for Auxiliary (or Helper) Methods public int length(){ return auxLength(head); } private int auxLength(Element element){ if(element == null) return 0; else return 1 + auxLength(element.next);

How Recursive Methods work Modern computer uses a stack as the primary memory management model for a running program.  Each running program has its own memory allocation containing the typical layout as shown below.

How Recursive Methods work When a method is called an Activation Record is created. It contains: The values of the parameters. The values of the local variables. The return address (The address of the statement after the call statement). The previous activation record address. A location for the return value of the activation record. When a method returns: The return value of its activation record is passed to the previous activation record or it is passed to the calling statement if there is no previous activation record. The Activation Record is popped entirely from the stack. Recursion is handled in a similar way. Each recursive call creates a separate Activation Record” As each recursive call completes, its Activation Record is popped from the stack. Ultimately control passes back to the calling statement.

Tracing of Recursive Methods A recursive method may be traced using the recursion tree it generates. Example1: Consider the recursive method f defined below. Draw the recursive tree generated by the call f("KFU", 2) and hence determine the number of activation records generated by the call and the output of the following program: public class MyRecursion3 { public static void main(String[] args){ f("KFU", 2); } public static void f(String s, int index){ if (index >= 0) { System.out.print(s.charAt(index)); f(s, index - 1);

Tracing of Recursive Methods Note: The red numbers indicate the order of execution The output is: UFKKFKKUFKKFKK The number of generated activation records is 15; it is the same as the number of generated recursive calls.

Tracing of Recursive Methods Example2: The Towers of Hanoi problem: A total of n disks are arranged on a peg A from the largest to the smallest; such that the smallest is at the top. Two empty pegs B and C are provided. It is required to move the n disks from peg A to peg C under the following restrictions: Only one disk may be moved at a time. A larger disk must not be placed on a smaller disk. In the process, any of the three pegs may be used as temporary storage. Suppose we can solve the problem for n – 1 disks. Then to solve for n disks use the following algorithm: Move n – 1 disks from peg A to peg B Move the nth disk from peg A to peg C Move n – 1 disks from peg B to peg C

Tracing of Recursive Methods This translates to the Java method hanoi given below: import java.io.*; public class TowersOfHanoi{ public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the value of n: " ); int n = Integer.parseInt(stdin.readLine()); hanoi(n, 'A', 'C', 'B'); } public static void hanoi(int n, char from, char to, char temp){ if (n == 1) System.out.println(from + " --------> " + to); else{ hanoi(n - 1, from, temp, to); hanoi(n - 1, temp, to, from);

Tracing of Recursive Methods Draw the recursion tree of the method hanoi for n = = 3 and hence determine the output of the above program. output of the program is: A -------> C A -------> B C -------> B B -------> A B -------> C