Chapter 2 Recursion: The Mirrors CS 302 - Data Structures Mehmet H Gunes Modified from authors’ slides.

Slides:



Advertisements
Similar presentations
Data Abstraction and Problem Solving with C++ Walls and Mirrors, Third Edition, Frank M. Carrano and Janet J. Prichard ©2002 Addison Wesley CHAPTER 2 Recursion:
Advertisements

Recursion Chapter 8. 2 Chapter Contents What Is Recursion? Tracing a Recursive Method Recursive Methods That Return a Value Recursively Processing an.
Recursion. Binary search example postponed to end of lecture.
© 2006 Pearson Addison-Wesley. All rights reserved3-1 Chapter 3 Recursion: The Mirrors CS102 Sections 51 and 52 Marc Smith and Jim Ten Eyck Spring 2008.
Programming with Recursion
Ch. 3: Recursion. Recursive Solutions Recursion –An extremely powerful problem-solving technique –Breaks a problem into smaller identical problems –An.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
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.
Recursion.
Recursion. Recursive Solutions Recursion breaks a problem into smaller identical problems – mirror images so to speak. By continuing to do this, eventually.
© 2006 Pearson Addison-Wesley. All rights reserved3-1 Chapter 3 Recursion: The Mirrors.
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.
COMPSCI 105 S Principles of Computer Science Recursion 3.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
CENG 7071 Recursion. CENG 7072 Recursion Recursion is a technique that solves a problem by solving a smaller problem of the same type. A recursive function.
Recursion CS Goals Discuss recursion as another form of repetition Do the following tasks, given a recursive routine Determine whether the routine.
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Recursion Chapter 7 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
1 Recursion Dr. Bernard Chen Ph.D. University of Central Arkansas.
Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Recursion: The Mirrors Chapter 2.
Recursion: The Mirrors Chapter 2 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
© 2006 Pearson Addison-Wesley. All rights reserved 3-1 Chapter 3 Recursion: The Mirrors.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-
Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Recursion: The Mirrors Chapter 2.
Chapter 3 Recursion: The Mirrors. © 2004 Pearson Addison-Wesley. All rights reserved 3-2 Recursive Solutions Recursion –An extremely powerful problem-solving.
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.
COSC 2006 Data Structures I Recursion II
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 2: Recursion: The Mirrors.
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.
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++
1 C++ Plus Data Structures Nell Dale Chapter 7 Programming with Recursion Slides by Sylvia Sorkin, Community College of Baltimore County - Essex Campus.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 2: Recursion: The Mirrors Data Abstraction & Problem Solving.
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 Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
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.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
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.
Data Structures I (CPCS-204) Week # 5: Recursion Dr. Omar Batarfi Dr. Yahya Dahab Dr. Imtiaz Khan.
递归算法的效率分析. 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.
Chapter 2 Recursion: The Mirrors. © 2005 Pearson Addison-Wesley. All rights reserved2-2 Recursive Solutions Recursion is an extremely powerful problem-solving.
Data Abstraction and Problem Solving with JAVA Walls and Mirrors Frank M. Carrano and Janet J. Prichard © 2001 Addison Wesley Data Abstraction and Problem.
Recursion Chapter 10 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Recursion Chapter 10 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
Recursion Powerful Tool
Programming with Recursion
Recursion.
Recursion CENG 707.
Recursion CENG 707.
Recursion: The Mirrors
Recursion: The Mirrors
Programming with Recursion
Chapter 18-3 Recursion Dale/Weems.
Recursion: The Mirrors
When a function is called...
Yan Shi CS/SE 2630 Lecture Notes
Chapter 18 Recursion.
Recursion: The Mirrors
Presentation transcript:

Chapter 2 Recursion: The Mirrors CS Data Structures Mehmet H Gunes Modified from authors’ slides

Contents Recursive Solutions Recursion That Returns a Value Recursion That Performs an Action Recursion with Arrays Organizing Data More Examples Recursion and Efficiency Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

Recursive Solutions Recursion breaks a problem into smaller identical problems Some recursive solutions are inefficient, impractical Complex problems can have simple recursive solutions Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

Recursive Solutions Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

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

Recursion You must be careful when using recursion. Recursive solutions are typically less efficient than iterative solutions. Still, many problems lend themselves to simple, elegant, recursive solutions. We must avoid making an infinite sequence of function calls – infinite recursion Avoid them !!!

Recursive Solutions A recursive solution calls itself Each recursive call solves an identical, smaller problem Test for base case enables recursive calls to stop Eventually one of smaller calls will be base case Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

General format for many recursive functions if (some condition for which answer is known) // base case solution statement else // general case recursive function call Each successive recursive call should bring you closer to a situation in which the answer is known. Each recursive algorithm must have at least one base case, as well as the general (recursive) case

Recursive Query

Recursive Solution

A Recursive Valued Function The factorial of n Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

A Recursive Valued Function fact(3) Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

The Box Trace Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 The beginning of the box trace

The Box Trace Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

The Box Trace Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

The Box Trace Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 The function writeBackwards

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward("cat")

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward("cat")

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012 Box trace of writeBackward("cat")

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013` Box trace of writeBackward("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward2("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward2("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward2("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward2("cat") in pseudocode

A Recursive Void Function Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace of writeBackward2("cat") in pseudocode

Writing an Array’s Entries in Backward Order Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Pseudocode

Writing an Array’s Entries in Backward Order Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Source code

RevPrint(listData); A B C D E FIRST, print out this section of list, backwards THEN, print this element listData

Using recursion with a linked list void RevPrint ( NodeType* listPtr ) /** Reverse print a linked listPtr points to an element of a all elements of list pointed to by listPtr have been printed out in reverse order. **/ { if ( listPtr != NULL ) // general case { RevPrint ( listPtr-> next ); // process the rest std::cout info << std::endl; // print this element } // Base case : if the list is empty, do nothing }

The Binary Search Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 A high-level binary search for the array problem

The Binary Search Issues to consider 1.How to pass a half array to recursive call 2.How to determine which half of array has target value 3.What is the base case? 4.How will result of binary search be indicated? Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

The Binary Search Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box traces of binarySearch with anArray = : (a) a successful search for 9

The Binary Search Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box traces of binarySearch with anArray = : (b) an unsuccessful search for 6

The Binary Search Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Box trace with a reference argument

Finding the Largest Value in an Array Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Recursive solution to the largest-value problem

Finding the Largest Value in an Array Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 The recursive calls that maxArray( ) generates

Finding the k th Smallest Value of an Array Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 The recursive solution proceeds by: 1.Selecting a pivot value in array 2.Cleverly arranging/partitioning, values in array about this pivot value 3.Recursively applying strategy to one of partitions

Finding the k th Smallest Value of an Array Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 A partition about a pivot

Finding the k th Smallest Value of an Array Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 High level pseudo code solution

Organizing Towers of Hanoi Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 (a) the initial state; (b) move n – 1 disks from A to C;

Towers of Hanoi Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 (c) move 1 disk from A to B; (d) move n – 1 disks from C to B

Towers of Hanoi Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Pseudocode solution

Towers of Hanoi Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 The order of recursive calls that results from solve Towers(3, A, B, C)

Towers of Hanoi Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Source code for solveTowers

Multiplying Rabbits Assumed “facts” about rabbits: Rabbits never die. A rabbit reaches maturity exactly two months after birth Rabbits always born in male-female pairs. At the beginning of every month, each mature male-female pair gives birth to exactly one male-female pair. Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

Multiplying Rabbits Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

Multiplying Rabbits (The Fibonacci Sequence) Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 to find the next number in the sequence, add together the previous two numbers

The Fibonacci Sequence (Multiplying Rabbits) Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 A C++ function to compute rabbit(n)

The Fibonacci Sequence (Multiplying Rabbits) Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 The recursive calls that rabbit(7) generates

An example where recursion comes naturally Combinations how many combinations of a certain size can be made out of a total group of elements

Combinations(4, 3)

Choosing k Out of n Things Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013 Recursive function:

Choosing k Out of n Things The recursive calls that g (4, 2) generates Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

Stack Activation Frames The activation record stores the return address for this function call, 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.

// Another recursive function int Func ( int a, int b ) // Pre: a and b have been assigned values // Post: Function value = ?? { int result; if ( b == 0 ) // base case result = 0; else { if ( b > 0 ) // first general case result = a + Func ( a, b - 1 ) ); // instruction 50 else // second general case result = Func ( - a, - b ); // instruction 70 } return result; } What operation does Func(a, b) simulate?

FCTVAL ? result ? b 2 a 5 Return Address 100 x = Func(5, 2); // original call is instruction 100 original call at instruction 100 pushes on this record for Func(5,2) Run-Time Stack Activation Records

FCTVAL ? result ? b 1 a 5 Return Address 50 FCTVAL ? result 5+Func(5,1) = ? b 2 a 5 Return Address 100 record for Func(5,2) call in Func(5,2) code at instruction 50 pushes on this record for Func(5,1) x = Func(5, 2); // original call at instruction 100 Run-Time Stack Activation Records

FCTVAL ? result ? b 0 a 5 Return Address 50 FCTVAL ? result 5+Func(5,0) = ? b 1 a 5 Return Address 50 FCTVAL ? result 5+Func(5,1) = ? b 2 a 5 Return Address 100 record for Func(5,2)record for Func(5,1) call in Func(5,1) code at instruction 50 pushes on this record for Func(5,0) Run-Time Stack Activation Records

FCTVAL 0 result 0 b 0 a 5 Return Address 50 FCTVAL ? result 5+Func(5,0) = ? b 1 a 5 Return Address 50 FCTVAL ? result 5+Func(5,1) = ? b 2 a 5 Return Address 100 record for Func(5,2) record for Func(5,1) record for Func(5,0) is popped first with its FCTVAL Run-Time Stack Activation Records

FCTVAL 5 result 5+Func(5,0) = 5+ 0 b 1 a 5 Return Address 50 FCTVAL ? result 5+Func(5,1) = ? b 2 a 5 Return Address 100 record for Func(5,2)record for Func(5,1) is popped next with its FCTVAL Run-Time Stack Activation Records

FCTVAL 10 result 5+Func(5,1) = 5+5 b 2 a 5 Return Address 100 x = Func(5, 2); // original call at line 100 record for Func(5,2) is popped last with its FCTVAL Run-Time Stack Activation Records

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 as in the next example.

// USES TAIL RECURSION bool ValueInList ( ListType list, int value, int startIndex ) /** Searches list for value between positions startIndex and list.info[ startIndex ].. list.info[ list.length - 1 ] contain values to be Function value = ( value exists in list.info[ startIndex ].. list.info[ list.length - 1 ] ) **/ { if ( list.info[startIndex] == value )// one base case return true; else { if (startIndex == list.length -1 ) // another base case return false; else return ValueInList( list, value, startIndex + 1 ); }

// ITERATIVE SOLUTION bool ValueInList ( ListType list, int value, int startIndex ) /** Searches list for value between positions startIndex and list.info[ startIndex ].. list.info[ list.length - 1 ] contain values to be Function value = ( value exists in list.info[ startIndex ].. list.info[ list.length - 1 ] ) { bool found = false; while ( !found && startIndex < list.length ) { if ( value == list.info[ startIndex ] ) found = true; else startIndex++; } return found; }

Recursion and Efficiency Inefficiency factors – Overhead associated with function calls – Inherent inefficiency of some recursive algorithms Principle: – Do not use recursive solution if inefficient and clear, efficient iterative solution exists Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013

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