Recursion Powerful Tool

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.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
Programming with 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.
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 CS Goals Discuss recursion as another form of repetition Do the following tasks, given a recursive routine Determine whether the routine.
1 Chapter 18-1 Recursion Dale/Weems. 2 Chapter 18 Topics l Meaning of Recursion l Base Case and General Case in Recursive Function Definitions l Writing.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
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.
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.
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.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
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.
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.
224 3/30/98 CSE 143 Recursion [Sections 6.1, ]
Computer Science Department Data Structure & Algorithms Lecture 8 Recursion.
Reading – Chapter 10. Recursion The process of solving a problem by reducing it to smaller versions of itself Example: Sierpinski’s TriangleSierpinski’s.
Review Introduction to Searching External and Internal Searching Types of Searching Linear or sequential search Binary Search Algorithms for Linear Search.
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.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
1 Recursion. 2 Chapter 15 Topics  Meaning of Recursion  Base Case and General Case in Recursive Function Definitions  Writing Recursive Functions with.
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.
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.
Recursion. Objectives At the conclusion of this lesson, students should be able to Explain what recursion is Design and write functions that use recursion.
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.
Programming with Recursion
Recursion.
Sections 4.1 & 4.2 Recursive Definitions,
Chapter 13 Recursion Copyright © 2016 Pearson, Inc. All rights reserved.
Chapter 19: Recursion.
Recursion Version 1.0.
Recursion DRILL: Please take out your notes on Recursion
Recursion: The Mirrors
Computer Science 4 Mr. Gerb
CSC 421: Algorithm Design & Analysis
CSC 421: Algorithm Design & Analysis
CSC 421: Algorithm Design & Analysis
Chapter 14 Recursion. Chapter 14 Recursion Overview 14.1 Recursive Functions for Tasks 14.2 Recursive Functions for Values 14.3 Thinking Recursively.
Programming with Recursion
Chapter 14: Recursion Starting Out with C++ Early Objects
Recursion "To understand recursion, one must first understand recursion." -Stephen Hawking.
Applied Algorithms (Lecture 17) Recursion Fall-23
CS 3343: Analysis of Algorithms
Chapter 14: Recursion Starting Out with C++ Early Objects
Chapter 18-3 Recursion Dale/Weems.
Basics of Recursion Programming with Recursion
When a function is called...
CSC 421: Algorithm Design & Analysis
Yan Shi CS/SE 2630 Lecture Notes
Chapter 18 Recursion.
Recursive Algorithms 1 Building a Ruler: drawRuler()
Recursion.
Presentation transcript:

Recursion Powerful Tool Useful in simplifying a problem (hides details of a problem) The ability of a function to call itself A recursive call is a function call in which the called function is the same as the one making the call. We must avoid making an infinite sequence of function calls (infinite recursion).

Recursion: Divide and Conquer Problem Solving Strategy 1) Divide problem (input instance) into one or more subproblems of exactly the same type as the original problem 2) Solve each subproblem 3) Combine solutions of subproblems to obtain a solution for original input NOTE: Looks like top-down design, except subproblems are the exactly the same type as the original problem

Finding a Recursive Solution Each successive recursive call should bring you closer to a situation in which the answer is known. A case for which the answer is known (and can be expressed without recursion) is called a base case. (The answer is usually known in the smallest version of the problem that requires the least amount of work, for example print out a list of only 1 element.) Each recursive algorithm must have at least one base case, as well as the general (recursive) case

General format for many recursive functions if (some condition for which answer is known) solution statement // base case else recursive function call // general case SOME EXAMPLES . . .

Writing a recursive function to find n! (factorial) DISCUSSION The function call Factorial(4) should have value 24, because it is 4 * 3 * 2 * 1 . For a situation in which the answer is known), the value of 0! is 1. So our base case could be along the lines of if ( number == 0 ) return 1;

cont. Now for the general case . . . The value of Factorial(n) can be written as n * the product of the numbers from (n - 1) to 1, that is, n * (n - 1) * . . . * 1 or, n * Factorial(n - 1) And notice that the recursive call Factorial(n - 1) gets us “closer” to the base case of Factorial(0).

Recursive Solution int Factorial ( int n) // Pre: number is initialized and number >= 0. { if ( n== 0) // base case return 1 ; else // general case return n * Factorial ( n- 1 ); }

Three-Question Method of Verifying Recursive Functions Base-Case Question: Is there a nonrecursive way out of the function that works? 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?

Factorial Example Base cases: number == 0 Recursive calls smaller returns 1 ….correct by definition Recursive calls smaller passes n-1 …check If we assume Factorial(n-1) gives us correct value of the n-1st factorial, and the assignment statement multiplies it by n …this is the definition of the nth Factorial number, so we know the function works for all n > 1. Therefore the function works. (Induction Proof)

Recursive function to determine if value is in array PROTOTYPE void DoRetrieveItem (ArrayType info, ItemType & item, bool & found, int start, int end); Already searched Needs to be searched 74 36 . . . 95 info[0] [1] [start] 75 29 47 . . . [length -1] index of current element to examine

//initial call to recursive private member function void RetrieveItem (ArrayType info, ItemType & item, bool & end) // Searches list for element with same key as item // Pre: item’s key is initialized // Post: if key of item exists in an item in the list, item will be set to that element and found will // be set to true, otherwise found will be set to false { //initial call to recursive private member function DoRetrieveItem (info, item, found, 0 ) ; } 11

else if ( info[start] == value ) // another base case void DoRetrieveItem (ArrayType info, ItemType & item, bool & found, int start, int end) // Searches list info for value between positions start and length-1 // Pre: the sublist, list.info[start ] . . list.info[ list.length-1] contain values to be searched // Post: if key of item exists in an item in the sublist info[start] . .. info[ list.end], item will // be set to that element and found will be set to true, otherwise found will be set to false { if (start == end ) // one base case return false ; else if ( info[start] == value ) // another base case { item = info [start]; return true ; } else // general case return DoRetrieveItem (info, item, found, start + 1, end) ; 12

found = false; // base case else mid = (start + end)/2; void DoRetrieveItem (ArrayType info, ItemType & item, bool & found, int start, int length) // Searches list for value between positions start and end // Pre: the sublist, list.info[start ] . . list.info[ list.end] contain values to be searched and is SORTED // Post: if key of item exists in an item in the sublist list.info[start] . .. list.info[ list.end], item will // be set to that element and found will be set to true, otherwise found will be set to false { int mid; if (start > end) found = false; // base case else mid = (start + end)/2; if (info[mid] == item ) // base case { item = info[mid]; found = true ; } else if (info[mid] < item ) // general case DoRetrieveItem (info, item, found, start, mid-1); else // general case DoRetrieveItem (info, item, found, mid+1, end); 13

“Why use recursion?” The first couple of examples could have been written without recursion, using iteration instead. The iterative solution uses a loop, and the recursive solution uses an if statement. However, for certain problems the recursive solution is the most natural solution. In a future example, you will see a function to print a stack in reverse. I will use both a loop and a temporary container. It is easier to solve this problem using recursion.

Tail Recursion The case in which a function contains only a single recursive call and it is the last statement to be executed in the function. Tail recursion can be replaced by iteration to remove recursion from the solution.

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 a return to the correct place in the calling block after the function code is executed. This correct place is called the return address. When any function is called, the run-time stack is used. On this stack is placed an activation record (stack frame) for the function call.

Stack Activation Frames The activation record stores the return address for this function call, and also the parameters, local variables, and the function’s return value, if non-void. The activation record for a particular function call is popped off the run-time stack when the final closing brace in the function code is reached, or when a return statement is reached in the function code. At this time the function’s return value, if non-void, is brought back to the calling block return address for use there.

Use a recursive solution when: The depth of recursive calls is relatively “shallow” compared to the size of the problem. The recursive version does about the same amount of work as the nonrecursive version. The recursive version is shorter and simpler than the nonrecursive solution. SHALLOW DEPTH EFFICIENCY CLARITY

void DoPrintBackwards (List<ItemType> & list); list data A B C D E FIRST, print out this section of list, backwards THEN, print this element

Base Case and General Case A base case may be a solution in terms of a “smaller” list. Certainly for a list with 0 elements, there is no more processing to do and is the easiest version of the problem to solve. Our general case needs to bring us closer to the base case situation. That is, the number of list elements to be processed decreases by 1 with each recursive call. By printing one element in the general case, and also processing the smaller remaining list, we will eventually reach the situation where 0 list elements are left to be processed. In the general case, we will print the elements of the smaller remaining list in reverse order, and then print the current item afterwards.

Using recursion with a linked list template <class ItemType> void DoPrintBackwards ( List <ItemType> & list) // Pre: None // Post: elements of list to right of cursor printed out in reverse // order. { ItemType item; // Understood Base case : if the list is at end, do nothing if ( ! list.AtEnd ( ) ) // General case list.GetNextItem (item); list.AdvanceCursor( ); //Advances currentPos DoPrintBackwards ( list ) ; // print rest of list cout << item << “ “; // print this element } 21