Recursion CS3240. 2 Goals Discuss recursion as another form of repetition Do the following tasks, given a recursive routine Determine whether the routine.

Slides:



Advertisements
Similar presentations
Recursion. Binary search example postponed to end of lecture.
Advertisements

Recursion CS 308 – Data Structures. What is recursion? smaller version Sometimes, the best way to solve a problem is by solving a smaller version of the.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Programming with Recursion
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.
Recursion.
1 Chapter 7 Recursion. 2 What Is Recursion? l Recursive call A method call in which the method being called is the same as the one making the call l Direct.
Recursion A recursive function is a function that calls itself either directly or indirectly through another function. The problems that can be solved.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
A Review of Recursion Dr. Jicheng Fu Department of Computer Science University of Central Oklahoma.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
1 Recursion Dr. Bernard Chen Ph.D. University of Central Arkansas.
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 Storage Classes, Scope, and Recursion Lecture 6.
12-CRS-0106 REVISED 8 FEB 2013 KUG1C3 Dasar Algoritma dan Pemrograman.
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.
Chapter 9: Recursion1 CHAPTER 9 RECURSION. Recursion  Concept of recursion  A recursive: Benefit and Cost  Comparison : Iterative and recursive functions.
Recursion.  A recursive function contains a call to itself Example: the factorial n!=n*(n-1)! for n>1 n!=1 for n=1 int factorial (int n) { if (n == 0)
1 Programming with Recursion. 2 Recursive Function Call A recursive call is a function call in which the called function is the same as the one making.
Recursion CS 3358 – Data Structures. Big Picture Our objective is to write a recursive program and convince ourselves it is correct with the minimum amount.
Stephen P. Carl - CS 2421 Recursion Reading : Chapter 4.
Cosc236/recursion1 Recursion Recursive method calls itself Recursion frequently occurs in mathematics Recursive definition –2 parts base part (basis) recursive.
1 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus and Robert Moyer, Montgomery County Community.
1 Lecture 14 Chapter 18 - Recursion. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 Chapter 13 Recursion. 2 Chapter 13 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing Recursive.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
CSE 1342 Programming Concepts Recursion. Overview of Recursion nRecursion is present when a function is defined in terms of itself. nThe factorial of.
CIS 068 Welcome to CIS 068 ! Stacks and Recursion.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Modified from the slides by Sylvia Sorkin, Community College of Baltimore County.
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.
Computer Science and Software Engineering University of Wisconsin - Platteville 9. Recursion Yan Shi CS/SE 2630 Lecture Notes Partially adopted from C++
Recursion CS 302 – Data Structures Chapter 7. What is recursion? smaller A technique that solves problem by solving smaller versions of the same problem!
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
Chapter 13 Recursion. Learning Objectives Recursive void Functions – Tracing recursive calls – Infinite recursion, overflows Recursive Functions that.
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.
Java Programming: Guided Learning with Early Objects Chapter 11 Recursion.
Recursion.
Recursion Unit 15. Recursion: Recursion is defined as the process of a subprogram calling itself as part of the solution to a problem. It is a problem.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
1 Lecture 3 Part 2 Storage Classes, Scope, and Recursion.
Tail Recursion l The case in which a function contains only a single recursive call and it is the last statement to be executed in the function. l Tail.
Chapter 7 Programming with Recursion. What Is Recursion? Recursive call A method call in which the method being called is the same as the one.
Chapter 6 Lists Plus Lecture 12. What is a Circular Linked List? A circular linked list is a list in which every node has a successor; the “last” element.
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.
Chapter 4 Recur ecur ecur ecursion. Chapter 4: Recursion 4.1 – Recursive Definitions, Algorithms and Programs 4.2 – The Three Questions 4.3 – Towers of.
12-CRS-0106 REVISED 8 FEB 2013 KUG1C3 Dasar Algoritma dan Pemrograman.
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.
递归算法的效率分析. When a function is called... A transfer of control occurs from the calling block to the code of the function --It is necessary that there be.
Welcome to Recursion! Say what?!? Recursion is… the process of solving large problems by simplifying them into smaller ones. similar to processing using.
Recursion Powerful Tool
Programming with Recursion
Recursion DRILL: Please take out your notes on Recursion
Computer Science 4 Mr. Gerb
Java 4/4/2017 Recursion.
Recursion Chapter 10.
Programming with Recursion
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Recursion Data Structures.
Module 1-10: Recursion.
When a function is called...
Yan Shi CS/SE 2630 Lecture Notes
Chapter 18 Recursion.
Recursion.
Presentation transcript:

Recursion CS3240

2 Goals Discuss recursion as another form of repetition Do the following tasks, given a recursive routine Determine whether the routine halts Determine the base case(s) Determine the general case(s) Determine what the routine does Determine whether the routine is correct and, if it is not, correct it

3 Goals Do the following tasks, given a simple recursive problem Determine the base case(s) Determine the general case(s) Design and code the solution as a recursive void or value-returning function Verify a recursive routine, according to the Three-Question Method Decide whether a recursive solution is appropriate for a problem

4 Goals Compare and contrast dynamic storage allocation and static storage allocation in relation to using recursion Explain how recursion works internally by showing the contents of the run-time stack Replace a recursive solution with iteration and/or the use of a stack Explain why recursion may or may not be a good choice to implement the solution to a problem

5 What Is Recursion? How is recursion like a set of Russian dolls?

6 What Is Recursion? Recursive call A method call in which the method being called is the same as the one making the call Direct recursion Recursion in which a method directly calls itself Indirect recursion Recursion in which a chain of two or more method calls returns to the method that originated the chain

7 Example of Recursion Recursive definition A definition in which something is defined in terms of a smaller version of itself What is 3 factorial?

8 Example of Recursion

9 Examples of Recursion

10 Example of Recursion Base case The case for which the solution can be stated nonrecursively General (recursive) case The case for which the solution is expressed in terms of a smaller version of itself Recursive algorithm A solution that is expressed in terms of (a) a smaller instance(s) of itself and (b) a base case(s)

11 Writing Recursive Solutions Algorithm for writing recursive solutions Determine the size of the problem Size is the factor that is getting smaller Size is usually a parameter to the problem Identify the base case(s) The case(s) for which you know the answer Identify the general case(s) The case(s) that can be expressed as a smaller version of the size

12 Writing Recursive Solutions Let’s try it Problem: Calculate X n (X to the nth power) Recursive formulation: X*(X n-1 )*(X n-2 )*...*X 0 What is the size of the problem? Which case do you know the answer to? Which case can you express as a smaller version of the size?

13 Writing Recursive Solutions int Power(int number, int exponent) { if (exponent == 0) return 1 else return number * Power(number, exponent - 1) } Do we need a precondition?

14 Writing Recursive Solutions Pattern of solution if (some condition for which answer is know) solution statement else function call Base case Recursive case

15 Writing Recursive Solutions Shall we try it again? Problem: Calculate Nth item in Fibonacci sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 What is the next number? What is the size of the problem? Which case do you know the answer to? Which case can you express as a smaller version of the size?

16 Writing Recursive Solutions int Fibonacci(int n) { if (n == 0 || n == 1) return n; else return Fibonacci(n-2) + Fibonacci(n-1); ) That was easy, but it is not very efficient. Why?

17 Verifying Recursive Solutions How can we “prove” that the solution works? Base-Case Question: Is there a nonrecursive way out of the function? Smaller-Caller Question: Does each recursive function call involve a smaller case of the original problem leading to the base case? General-Case Question: Assuming each recursive call works correctly, does the whole function work correctly? Can you answer yes to all three questions?

18 Verifying Recursive Solutions int Power(int number, int exponent) { if (exponent == 0) return 1 else return number * Power(number, exponent - 1) } Is there a nonrecursive way out? Does each call involve a small case of original? Assuming recursive call works, does the entire function work?

19 Writing Recursive Solutions Shall we try it again? Problem: Search a list of integers for a value and return true if it is in the list and false otherwise What is the size of the problem?

20 Writing Recursive Solutions bool ValueInList(ListType data, int value, int startIndex); Which case do you know the answer to? Which case can you express as a smaller version of the size?

21 Writing Recursive Solutions bool ValueInList(ListType list, int value, int startIndex { if (list.info[startIndex] == value) return true; else if (startIndex == list.length -1) return false; else return ValueInList(list, value, startIndex + 1); } Base Case 1 Base Case 2 Recursive Case

22 Writing Recursive Solutions Why use recursion? True, these examples could more easily be solved using iteration However, a recursive solution is a natural solution in certain cases, especially when pointers are involved

23 Writing Recursive Solutions Printing a list in order Size? Base case? Recursive (general) case?

24 Writing Reverse Solutions void Print(NodeType* listPtr) { if (listPtr != NULL) { std::cout info << std::endl; Print(listPrt->next); } Where is the base case?

25 Writing Recursive Solutions Printing a list in reverse order What must be changed from the in-order print to make the code print in reverse order?

26 Writing Recursive Solutions Can you verify the RevPrint algorithm using the three-question method? Base-Case question? Smaller-Caller Question? General-Case Question?

27 bool Mystery( ItemType info[ ], ItemType item, int fromLoc, int toLoc ) { int mid; if ( fromLoc > toLoc ) return false; else { mid = ( fromLoc + toLoc ) / 2 ; if (info[mid] == item) return true ; else if (item < info[mid]) return Mystery (info, item, fromLoc, mid-1 ); else return Mystery(info, item, mid + 1, toLoc) ; } What does this function return?

28 Writing Recursive Solutions Problem: Insert item into list What is the size of the problem? Which case(s) do you know the answer to? Which case can you express as a smaller version of the size?

29 Writing Recursive Solutions void Insert(NodeType*& listPtr, ItemType item) { if (listPtr == NULL || item info) { NodeType* tempPtr = listPtr; listPtr = new NodeType; listPtr->info = iten; listPtr->next = tempPtr; } else Insert(listPtr->next, item) } NodeType*&: Is the *& important?

30 How Recursion Works Binding Time The time at which a variable is assigned to a memory address Static Storage Allocation Binding occurs during compilation Dynamic Storage Allocation Binding occurs during run time Global variables are bound at compile time. When are parameters bound to an address?

31 How Recursion Works Transfer of Control When a function is called, control is passed to the first executable statement in the function How does control get passed back to the calling code? Return Address The address of the instruction in the calling code that immediately follows the function call How does the function access the return address?

32 How Recursion Works Activation Record (Stack Frame) A record used at run time to store information about a function call, including the parameters, local variables, return address, and function return value (if a value-returning function) Run-time Stack A data structure that keeps track of activation records during the execution of a program

33 How Recursion Works Function Factorial loaded in memory

34 How Recursion Works answer = Factorial(4); return number * Factorial(number-1);

35 How Recursion Wroks return number * Factorial(number-1);(2) return number * Factorial(number-1);(1) return number * Factorial(number-1);(0) So now what?

36 How Recursion Works return number * Factorial(number-1);(2) return number * Factorial(number-1);(1) popped return number * Factorial(number-1);(0) popped

37 How Recursion Works return number * Factorial(number-1);(4) return number * Factorial(number-1);(3) popped return number * Factorial(number-1);(2) popped result from previous call (6) is multiplied by current number giving 24. Now what happens?

38 How Recursion Works void Insert(NodeType*& listPtr, ItemType item) Did you figure out why it must be NodeType*& ? Let’s trace Insert(listData, 11)

39 How Recursion Works R0 is non- recursive call

40 How Recursion Works listPtr->next = tempPtr; See why it works ?

41 Removing Recursion Tail Recursion The case in which a function contains only a single recursive invocation and it is the last statement to be executed in the function A tail recursive function can be replaced with iteration Stacking Using a stack to keep track of each local environment, i.e., simulate the run-time stack

42 When To Use Recursion Depth of recursive calls is relatively “shallow” compared to the size of the problem Recursive version does about the same amount of work as the nonrecursive version (same Big-O) The recursive version is shorter and simpler than the nonrecursive solution SHALLOW DEPTH EFFICIENCY CLARITY