CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem.

Slides:



Advertisements
Similar presentations
Types of Recursive Methods
Advertisements

Factorial Recursion stack Binary Search Towers of Hanoi
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.
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.
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. 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.
Chapter 10 Recursion. Copyright © 2005 Pearson Addison-Wesley. All rights reserved Chapter Objectives Explain the underlying concepts of recursion.
1 Chapter 18 Recursion Dale/Weems/Headington. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions.
Recursive Algorithms Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 106 Introduction to Computer Science I 03 / 28 / 2008 Instructor: Michael Eckmann.
28-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.
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.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Analysis of Algorithm Lecture 3 Recurrence, control structure and few examples (Part 1) Huma Ayub (Assistant Professor) Department of Software Engineering.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Recursion Review.
1 Recursion Dr. Bernard Chen Ph.D. University of Central Arkansas.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 Recursion.
Recursion. Basic problem solving technique is to divide a problem into smaller subproblems These subproblems may also be divided into smaller subproblems.
Recursion. Basic problem solving technique is to divide a problem into smaller sub problems These sub problems may also be divided into smaller sub problems.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
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.
Copyright © 2011 Pearson Education, Inc. Starting Out with Java: Early Objects Fourth Edition by Tony Gaddis Chapter 14: Recursion.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Programming Principles II Lecture Notes 5 Recursion Andreas Savva.
CHAPTER 02 Recursion Compiled by: Dr. Mohammad Omar Alhawarat.
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.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data Depends.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
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.
1 7.Algorithm Efficiency What to measure? Space utilization: amount of memory required  Time efficiency: amount of time required to process the data.
Dale Roberts CSCI N305 Functions Recursion Department of Computer and Information Science, School of Science, IUPUI.
CSC 221: Recursion. Recursion: Definition Function that solves a problem by relying on itself to compute the correct solution for a smaller version of.
Edited by Malak Abdullah Jordan University of Science and Technology Data Structures Using C++ 2E Chapter 6 Recursion.
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.
Recursion A recursive definition is one which uses the word or concept being defined in the definition itself Example: “A computer is a machine.
Pei Zheng, Michigan State University 1 Chapter 8 Recursion.
1 Chapter 8 Recursion. 2 Recursive Function Call a recursion function is a function that either directly or indirectly makes a call to itself. but we.
1 Recursion Recursive function: a function that calls itself (directly or indirectly). Recursion is often a good alternative to iteration (loops). Its.
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.
Tail and Non-tail Recursion Tail Recursion? –Definition –Advantages of tail recursion –Converting to and from tail recursion Indirect Recursion? –Definition.
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 Powerful Tool
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,
Chapter Topics Chapter 16 discusses the following main topics:
CprE 185: Intro to Problem Solving (using C)
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.
More on Recursive Methods
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.
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Applied Algorithms (Lecture 17) Recursion Fall-23
Recursion Data Structures.
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,
Dr. Sampath Jayarathna Cal Poly Pomona
Types of Recursive Methods
Presentation transcript:

CMSC 2021 Recursion Recursive Definition – one that defines something in terms of itself Recursion – A technique that allows us to break down a problem in to one or more subproblems that are similar in form to the original problem. Either the problem or the associated data can be recursive in nature

CMSC 2022 Iterative Factorial Iterative definition N! = N * (N-1) * (N-2) * … * 3 * 2 * 1 int factorial (int n) { int i, result; result = 1; for (i = 1; i <= n; i++) { result = result * i; } return ( result ); }

CMSC 2023 Recursive Factorial Recursive N! definition N! = 1 if N = 0 = N * (N-1)! Otherwise int factorial ( int n) { if (n == 0) return (1); return (n * factorial(n - 1) ); }

CMSC 2024 Iterative vs Recursive factorial Iterative 1.2 local variables 2.3 statements 3.Saves solution in an intermediate variable Recursive 1. No local variables 2. One statement 3. Returns result in single expression Recursion simplifies factorial by making the computer do the work. What work and how is it done?

CMSC 2025 How does it work? Each recursive call creates an “activation record” which contains local variables and parameters return address and is saved on the stack.

CMSC 2026 Iterative Power Iterative definition X N = X * X *X ….. * X (N factors) double power(double number, int exponent) { double p = 1; for (int i = 1; i <= exponent; i++) p = p * p; return (p); }

CMSC 2027 Recursive Power Recursive definition X N = 1 if N = 0 = X * X (N-1) otherwise double power(double number, int exponent) // Precondition: exponent >= 0 { if (exponent == 0) return (1); return (number * power(number, exponent-1)); }

CMSC 2028 Recursive String Reversal void RString (char *s, int len) { if (len <= 0) return; RString (s+1, len-1); cout << *s ; }

CMSC 2029 Recursive Data Structures Array -- a set of data elements store in contiguous memory cells Array -- zero elements OR a single data element OR an array followed by a single element

CMSC Iteratively Sum an Array int SumArray (int a[ ], int size) { int j, sum = 0; for ( j = 0; j < size; j++ ) sum += a[ j ]; return sum; }

CMSC Recursively Sum an Array int SumArray ( int a [ ], int size) { if (size == 0) return 0; else return array[ size – 1] + SumArray (a, size – 1); }

CMSC Approach to Writing Recursive Functions Using “factorial” as an example, 1.Write the function header so that you are sure what the function will do and how it will be called. [For factorial, we want to send in the integer for which we want to compute the factorial. And we want to receive the integer result back.] int factorial(int n)

CMSC Approach (cont’d) 2. Decompose the problem into subproblems (if necessary). For factorial, we must compute (n-1)! 3. Write recursive calls to solve those subproblems whose form is similar to that of the original problem. There is a recursive call to write: factorial(n-1) ; ]

CMSC Approach (cont’d) 4. Write code to combine, augment, or modify the results of the recursive call(s) if necessary to construct the desired return value or create the desired side effects. When a factorial has been computed, the result must be multiplied by the current value of the number for which the factorial was taken: return (n * factorial(n-1));

CMSC Approach (cont’d) 5. Write base case(s) to handle any situations that are not handled properly by the recursive portion of the program. The base case for factorial is that if n=0, the factorial is 1: if (n == 0) return(1);

CMSC Ensuring that Recursion Works Using “factorial” as an example, 1. A recursive subprogram must have at least one base case and one recursive case (it's OK to have more than one base case and/or more than one recursive case). The first condition is met, because if (n==0) return 1 is a base case, while the "else" part includes a recursive call (factorial(n-1)).

CMSC Does It Work? (cont’d) 2. The test for the base case must execute before the recursive call. If we reach the recursive call, we must have already evaluated if (n==0); this is the base case test, so this criterion is met.

CMSC Does It Work? (cont’d) 3. The problem must be broken down in such a way that the recursive call is closer to the base case than the top-level call. The recursive call is factorial(n-1). The argument to the recursive call is one less than the argument to the top-level call to factorial. It is, therefore, “closer” to the base case of n=0.

CMSC Does It Work? (cont’d) 4. The recursive call must not skip over the base case. Because n is an integer, and the recursive call reduces n by just one, it is not possible to skip over the base case.

CMSC Does It Work? (cont’d) 5. The non-recursive portions of the subprogram must operate correctly. Assuming that the recursive call works properly, we must now verify that the rest of the code works properly. We can do this by comparing the code with our definition of factorial. This definition says that if n=0 then n! is one. Our function correctly returns 1 when n is 0. If n is not 0, the definition says that we should return (n-1)! * n. The recursive call (which we now assume to work properly) returns the value of n-1 factorial, which is then multiplied by n. Thus, the non--recursive portions of the function behave as required.

CMSC Recursion vs. Iteration Recursion  Usually less code – algorithm can be easier to follow (Towers of Hanoi, binary tree traversals, flood fill)  Some mathematical and other algorithms are naturally recursive (factorial, summation, series expansions, recursive data structure algorithms)

CMSC Recursion vs. Iteration (cont’d) Iteration  Use when the algorithms are easier to write, understand, and modify (especially for beginning programmers)  Generally, runs faster because there is no stack I/O  Sometimes are forced to use iteration because stack cannot handle enough activation records (power(2, 5000))

CMSC Direct Recursion A C function is directly recursive if it contains an explicit call to itself Int foo (int x) { if ( x <= 0 ) return x; return foo ( x – 1); }

CMSC Indirect Recursion A C function foo is indirectly recursive if it contains a call to another function that ultimately calls foo. int foo (int x){ if (x <= 0) return x; return bar(x); } int bar (int y) { return foo (y – 1); }

CMSC Tail Recursion A recursive function is said to be tail recursive if there is no pending operations performed on return from a recursive call Tail recursive functions are often said to “return the value of the last recursive call as the value of the function”

CMSC factorial is non-tail recursive int factorial (int n) { if (n == 0) return 1; return n * factorial(n – 1); } Note the “pending operation” (namely the multiplication) to be performed on return from each recursive call

CMSC Tail recursive factorial int fact_aux (int n, int result) { if (n == 1) return result; return fact_aux (n – 1, n * result); } factorial (int n) { return fact_aux (n, 1); }

CMSC Linear Recursion A recursive function is said to be linearly recursive when no pending operation invokes another recursive call to the function. int factorial (int n) { if (n == 0) return 1; return n * factorial ( n – 1); }

CMSC Linear Recursive Count_42s int count_42s(int array[ ], int n) { if (n == 0) return 0; if (array[ n-1 ] != 42) { return (count_42s( array, n-1 ) ); } return (1 + count_42s( array, n-1) ); }

CMSC Tree Recursion A recursive function is said to be tree recursive (or non- linearly recursive when the pending operation does invoke another recursive call to the function. The Fibonacci function fib provides a classic example of tree recursion.

CMSC Fibonacci Numbers The Fibonacci numbers can be recursively defined by the rule: fib(n) = 0 if n is 0, = 1 if n is 1, = fib(n-1) + fib(n-2) otherwise For example, the first seven Fibonacci numbers are Fib(0) = 0 Fib(1) = 1 Fib(2) = Fib(1) + Fib(0) = 1 Fib(3) = Fib(2) + Fib(1) = 2 Fib(4) = Fib(3) + Fib(2) = 3 Fib(5) = Fib(4) + Fib(3) = 5 Fib(6) = Fib(5) + Fib(4) = 8

CMSC Tree Recursive Fibonacci // Note how the pending operation (the +) // needs a 2 nd recursive call to fib int fib(int n) { if (n == 0) return 0; if (n == 1) return 1; return ( fib ( n – 1 ) + fib ( n – 2 ) ); }

CMSC Tree Recursive Count_42s int count_42s(int array[ ], int low, int high) { if ((low > high) || (low == high && array[low] != 42)) { return 0 ; } if (low == high && array[low] == 42) { return 1; } return (count_42s(array, low, (low + high)/2) + count_42s(array, 1 + (low + high)/2, high)) ); }

CMSC Converting Recursive Functions to Tail Recursion A non-tail recursive function can often be converted to a tail recursive function by means of an “auxiliary” parameter that is used to form the result. The idea is to incorporate the pending operation into the auxiliary parameter in such a way that the recursive call no longer has a pending operations (is tail recursive)

CMSC Tail Recursive Fibonacci int fib_aux ( int n, int next, int result ) { if ( n == 0 ) return result; return ( fib_aux ( n - 1, next + result, next )); } int fib ( int n ) { return fib_aux ( n, 1, 0 ); }

CMSC Converting Tail Recursive Functions to Iterative Let’s assume that any tail recursive function can be expressed in the general form F ( x ) { if ( P( x ) ) return G( x ); return F ( H( x ) ); }

CMSC Tail Recursive to Iterative (cont’d) P( x ) is the base case of F(x) If P(x) is true, then the value of F(x) is the value of some other function, G(x). If P(x) is false, then the value of F(x) is the value of the function F on some other value H(x).

CMSC Tail Recursive to Iterative (cont’d) F( x ) { int temp_x; while ( P(x) is not true ) { temp_x = x; x = H (temp_x); } return G ( x );

CMSC Example – tail recursive factorial int fact_aux (int n, int result) { if (n == 1) return result; return fact_aux (n – 1, n * result) } F = fact_aux x is really two params – n and result value of P(n, result) is value of (n == 1) value of G(n, result) is result value of H(n, result) is (n – 1, n * result)

CMSC Iterative factorial int fact_aux (int n, int result) { int temp_n, temp_result; while ( n != 1 ) { // while P(x) not true temp_n = n;// temp_x = x (1) temp_result = result;// temp_x = x (2) n = temp_n – 1;// H (temp_x) (1) result = temp_n * temp_result;// H (temp_x) (2) } return result;// G (x) }

CMSC Converting Iteration to Tail Recursion Just like it’s possible to convert tail- recursion into iteration, it’s possible to convert any iterative loop into the combination of a recursive function and a call to that function

CMSC A while-loop example The following code fragment uses a while loop to read values into an integer array until EOF occurs, counting the number of integers read. nt nums [MAX]; int count = 0; while (scanf (“%d”, &nums[count]) != EOF) count++;

CMSC While loop example (cont’d) The key to implementing the loop using tail recursion is to determine which variables capture the “state” of the computation and use these variables as parameters to the tail recursive subprogram. count – the number of integers read so far nums -- the array that stores the integers

CMSC While loop example (cont’d) Since we are interested in getting the final value for count, we will write a function that returns count as its result. If the termination condition ( EOF ) is not true, the function increments count, reads a number into nums and calls itself recursively to to input the remainder of the numbers. If the termination condition is true, the function simply returns the final value of count.

CMSC While loop example (cont’d) int read_nums (int count, int nums[ ] ) { if (scanf (“%d”, &nums[count] != EOF)) return read_nums (count + 1, nums); return count; }

CMSC While loop example (cont’d) To call the function, we must pass in the appropriate initial values count = read_nums (0, nums);

CMSC Converting Iteration to Tail recursion Determining the variables used by the loop Writing tail-recursive function with one parameter for each variable Using the loop-termination condition as the base case

CMSC Converting Iteration to Tail recursion (cont’d) Determining how each variable changes from one iteration to the next and handing the sequence of expressions that represent those changes to the recursive call Replacing the iterative loop with a call to the tail recursive function with appropriate initial values

CMSC An exercise for the Student Convert the following for loop that finds the maximum value in an array to be tail recursive. Assume that the function max( ) returns the larger of the two parameters returned to it. int nums[MAX];// filled by some other function int max_num = nums[ 0 ]; for (j = 0; j < MAX; j++) max_num = max (max_num, nums[ j ] );

CMSC Floodfill void Image::floodfill(int x, int y) { if (x = numRows || y = numCols) return; if (a[x][y] == '1') return; if (a[x][y] == '0') a[x][y] = '1'; floodfill(x+1, y); // Go up floodfill(x-1, y); // Go down floodfill(x, y-1); // Go left floodfill(x, y+1); // Go right }