More on Recursive Methods

Slides:



Advertisements
Similar presentations
Types of Recursive Methods
Advertisements

Recursion Outline of the upcoming lectures: Review of Recursion
Tail and Non-tail Recursion
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
More on Recursive Methods KFUPM- ICS Data Structures.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
More on Recursive Recursion vs. Iteration Why Recursion?
Recursion Outline of the upcoming lectures: –Review of Recursion –Types of Recursive Methods –Final Remarks on Recursion.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
ICS103 Programming in C Lecture 11: Recursive Functions
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
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.
90-723: Data Structures and Algorithms for Information Processing Copyright © 1999, Carnegie Mellon. All Rights Reserved. Some Notes on Recursion Data.
Stacks & Recursion. Stack pushpop LIFO list - only top element is visible top.
CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
Chapter 12 Recursion, Complexity, and Searching and Sorting
ASET RECURSION. ASET RECURSIVE FUNCTIONS A recursive function is a function that calls itself to solve a smaller version of its task until a final call.
ICS220 – Data Structures and Algorithms Dr. Ken Cosh Week 5.
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.
Chapter 4 Recursion. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Explain the underlying concepts of recursion.
Recursion. What is recursion? Rules of recursion Mathematical induction The Fibonacci sequence Summary Outline.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Data Structures R e c u r s i o n. Recursive Thinking Recursion is a problem-solving approach that can be used to generate simple solutions to certain.
1 Recursion Recursion is a powerful programming technique that provides elegant solutions to certain problems. Chapter 11 focuses on explaining the underlying.
Recursion Chapter 17 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
Tail and Non-tail Recursion Tail Recursion? –Definition –Advantages of tail recursion –Converting to and from tail recursion Indirect Recursion? –Definition.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Recursion,
Ms N Nashandi Dr SH Nggada Week 08 – Recursion. Outline We shall be covering the following What is a recursion? Iteration versus Recursion. Recursion.
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
CS212: Data Structures and Algorithms
Recursion.
Recursion Data Structure Submitted By:- Dheeraj Kataria.
Chapter Topics Chapter 16 discusses the following main topics:
Chapter 15 Recursion.
CprE 185: Intro to Problem Solving (using C)
RECURSION.
Data Structures and Algorithms
RECURSION.
Computer Science 4 Mr. Gerb
More on Recursive Recursion vs. Iteration Why Recursion?
Unit 5 Recursion King Fahd University of Petroleum & Minerals
Chapter 15 Recursion.
Methods Chapter 6.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Java Software Structures: John Lewis & Joseph Chase
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
Announcements Final Exam on August 17th Wednesday at 16:00.
Recursive Thinking Chapter 9 introduces the technique of recursive programming. As you have seen, recursive programming involves spotting smaller occurrences.
Chapter 5 - Functions Outline 5.1 Introduction
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Recursion Chapter 11.
Programming application CC213
Stacks & Recursion.
CS201: Data Structures and Discrete Mathematics I
Recursion Data Structures.
Announcements Final Exam on August 19th Saturday at 16:00.
Unit 3 Test: Friday.
Module 1-10: Recursion.
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
Recursion Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves,
Java Programming: Chapter 9: Recursion Second Edition
Yan Shi CS/SE 2630 Lecture Notes
Dr. Sampath Jayarathna Cal Poly Pomona
ICS103 Programming in C Lecture 11: Recursive Functions
Types of Recursive Methods
Presentation transcript:

More on Recursive Methods KFUPM- ICS 202 -073 Data Structures

Outline Types of Recursive Methods Direct and Indirect Recursive Methods Nested and Non-Nested Recursive Methods Tail and Non-Tail Recursive Methods Linear and Tree Recursive Methods Excessive Recursion Recursion vs. Iteration Why Recursion? Common Errors in Writing Recursive Methods

Types of Recursive Methods A recursive method is characterized based on: Whether the method calls itself or not (direct or indirect recursion). Whether the recursion is nested or not. Whether there are pending operations at each recursive call (tail-recursive or not). The shape of the calling pattern -- whether pending operations are also recursive (linear or tree-recursive). Whether the method is excessively recursive or not.

Direct and Indirect Recursive Methods A method is directly recursive if it contains an explicit call to itself. A method x is indirectly recursive if it contains a call to another method which in turn calls x. They are also known as mutually recursive methods: long factorial (int x) { if (x == 0) return 1; else return x * factorial (x – 1); } public static boolean isEven(int n) { if (n==0) return true; else return(isOdd(n-1)); } public static boolean isOdd(int n) { return (! isEven(n));

Direct and Indirect Recursive Methods Another example of mutually recursive methods:

Direct and Indirect Recursive Methods public static double sin(double x){ if(x < 0.0000001) return x - (x*x*x)/6; else{ double y = tan(x/3); return sin(x/3)*((3 - y*y)/(1 + y*y)); } public static double tan(double x){ return sin(x)/cos(x); public static double cos(double x){ double y = sin(x); return Math.sqrt(1 - y*y);

Nested and Non-Nested Recursive Methods Nested recursion occurs when a method is not only defined in terms of itself; but it is also used as one of the parameters: Example: The Ackerman function The Ackermann function grows faster than a multiple exponential function. public static long Ackmn(long n, long m){ if (n == 0) return m + 1; else if (n > 0 && m == 0) return Ackmn(n – 1, 1); else return Ackmn(n – 1, Ackmn(n, m – 1)); }

Tail and Non-Tail Recursive Methods A method is tail recursive if in each of its recursive cases it executes one recursive call and if there are no pending operations after that call. Example 1: Example 2: public static void f1(int n){ System.out.print(n + " "); if(n > 0) f1(n - 1); } public static void f3(int n){ if(n > 6){ System.out.print(2*n + " "); f3(n – 2); } else if(n > 0){ System.out.print(n + " "); f3(n – 1); }

Tail and Non-Tail Recursive Methods Example of non-tail recursive methods: Example 1: After each recursive call there is a pending System.out.print(n + " ") operation. Example 2: After each recursive call there is a pending * operation. public static void f4(int n){ if (n > 0) f4(n - 1); System.out.print(n + " "); } long factorial(int x) { if (x == 0) return 1; else return x * factorial(x – 1); }

Converting tail-recursive method to iterative It is easy to convert a tail recursive method into an iterative one: Tail recursive method Corresponding iterative method public static void f1(int n) { System.out.print(n + " "); if (n > 0) f1(n - 1); } public static void f1(int n) { for( int k = n; k >= 0; k--) System.out.print(k + " "); } public static void f3 (int n) { if (n > 6) { System.out.print(2*n + " "); f3(n – 2); } else if (n > 0) { System.out.print(n + " "); f3 (n – 1); } public static void f3 (int n) { while (n > 0) { if (n > 6) { System.out.print(2*n + " "); n = n – 2; } else if (n > 0) { System.out.print(n + " "); n = n – 1; }

Why tail recursion? It is desirable to have tail-recursive methods, because: The amount of information that gets stored during computation is independent of the number of recursive calls. Some compilers can produce optimized code that replaces tail recursion by iteration (saving the overhead of the recursive calls). Tail recursion is important in languages like Prolog and Functional languages like Clean, Haskell, Miranda, and SML that do not have explicit loop constructs (loops are simulated by recursion).

Converting non-tail to tail recursive method A non-tail recursive method can often be converted to a tail-recursive method by means of an "auxiliary" parameter. This parameter is used to form the result. The idea is to attempt to incorporate the pending operation into the auxiliary parameter in such a way that the recursive call no longer has a pending operation. The technique is usually used in conjunction with an "auxiliary" method. This is simply to keep the syntax clean and to hide the fact that auxiliary parameters are needed.

Converting non-tail to tail recursive method Example 1: Converting non-tail recursive factorial to tail-recursive factorial We introduce an auxiliary parameter result and initialize it to 1. The parameter result keeps track of the partial computation of n! : long factorial (int n) { if (n == 0) return 1; else return n * factorial (n – 1); } public long tailRecursiveFact (int n) { return factAux(n, 1); } private long factAux (int n, int result) { if (n == 0) return result; else return factAux(n-1, n * result);

Converting non-tail to tail recursive method Example 2: Converting non-tail recursive fib to tail-recursive fib The fibonacci sequence is: 0 1 1 2 3 5 8 13 21 . . . Each term except the first two is a sum of the previous two terms. Because there are two recursive calls, a tail-recursive fibonacci method can be implemented by using two auxiliary parameters for accumulating results: int fib(int n){ if (n == 0 || n == 1) return n; else return fib(n – 1) + fib(n – 2); }

Converting non-tail to tail recursive method int fib (int n) { return fibAux(n, 1, 0); } int fibAux (int n, int next, int result) { if (n == 0) return result; else return fibAux(n – 1, next + result, next);

Linear and Tree Recursive Methods Another way to characterize recursive methods is by the way in which the recursion grows. The two basic ways are "linear" and "tree." A recursive method is said to be linearly recursive when no pending operation involves another recursive call to the method. For example, the factorial method is linearly recursive. The pending operation is simply multiplication by a variable, it does not involve another call to factorial. long factorial (int n) { if (n == 0) return 1; else return n * factorial (n – 1); }

Linear and Tree Recursive Methods A recursive method is said to be tree recursive when the pending operation involves another recursive call. The Fibonacci method fib provides a classic example of tree recursion. int fib(int n){ if (n == 0 || n == 1) return n; else return fib(n – 1) + fib(n – 2); }

Excessive Recursion A recursive method is excessively recursive if it repeats computations for some parameter values. Example: The call fib(6) results in two repetitions of f(4). This in turn results in repetitions of fib(3), fib(2), fib(1) and fib(0):

Recursion vs. Iteration In general, an iterative version of a method will execute more efficiently in terms of time and space than a recursive version. This is because the overhead involved in entering and exiting a function in terms of stack I/O is avoided in iterative version. Sometimes we are forced to use iteration because stack cannot handle enough activation records - Example: power(2, 5000))

Why Recursion? Usually recursive algorithms have less code, therefore algorithms can be easier to write and understand - e.g. Towers of Hanoi. However, avoid using excessively recursive algorithms even if the code is simple. Sometimes recursion provides a much simpler solution. Obtaining the same result using iteration requires complicated coding - e.g. Quicksort, Towers of Hanoi, etc. Recursive methods provide a very natural mechanism for processing recursive data structures. A recursive data structure is a data structure that is defined recursively – e.g. Tree. Functional programming languages such as Clean, FP, Haskell, Miranda, and SML do not have explicit loop constructs. In these languages looping is achieved by recursion.

Why Recursion? Some recursive algorithms are more efficient than equivalent iterative algorithms. Example: public static long power1 (int x, int n) { long product = 1; for (int i = 1; i <= n; i++) product *= x; return product; } public static long power2 (int x, int n) { if (n == 1) return x; else if (n == 0)return 1; else { long t = power2(x , n / 2); if ((n % 2) == 0) return t * t; else return x * t * t; }

Common Errors in Writing Recursive Methods The method does not call itself directly or indirectly. Non-terminating Recursive Methods (Infinite recursion): No base case. The base case is never reached for some parameter values. int badFactorial(int x) { return x * badFactorial(x-1); } int anotherBadFactorial(int x) { if(x == 0) return 1; else return x*(x-1)*anotherBadFactorial(x -2); // When x is odd, we never reach the base case!! }

Common Errors in Writing Recursive Methods Post increment and decrement operators must not be used since the update will not occur until AFTER the method call - infinite recursion. Local variables must not be used to accumulate the result of a recursive method. Each recursive call has its own copy of local variables. public static int sumArray (int[ ] x, int index) { if (index == x.length)return 0; else return x[index] + sumArray (x, index++); } public static int sumArray (int[ ] x, int index) { int sum = 0; if (index == x.length)return sum; else { sum += x[index]; return sumArray(x,index + 1); }

Common Errors in Writing Recursive Methods Wrong placement of return statement. Consider the following method that is supposed to calculate the sum of the first n integers: When result is initialized to 0, the method returns 0 for whatever value of the parameter n. The result returned is that of the final return statement to be executed. Example: A trace of the call sum(3, 0) is: public static int sum (int n, int result) { if (n >= 0) sum(n - 1, n + result); return result; }

Common Errors in Writing Recursive Methods A correct version of the method is: Example: A trace of the call sum(3, 0) is: public static int sum(int n, int result){ if (n == 0) return result; else return sum(n-1, n + result); }

Common Errors in Writing Recursive Methods The use of instance or static variables in recursive methods should be avoided. Although it is not an error, it is bad programming practice. These variables may be modified by code outside the method and cause the recursive method to return wrong result. public class Sum{ private int sum; public int sumArray(int[ ] x, int index){ if(index == x.length) return sum; else { sum += x[index]; return sumArray(x,index + 1); }