Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Chapter 2 Recursion: The Mirrors CS 302 - Data Structures Mehmet H Gunes Modified from authors’ slides."— Presentation transcript:

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

2 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

3 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

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

5 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

6 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 !!!

7 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

8 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

9 Recursive Query

10

11 Recursive Solution

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

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

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

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

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

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

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

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

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

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

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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 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

32 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

33 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

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

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

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

37 Using recursion with a linked list void RevPrint ( NodeType* listPtr ) /** Reverse print a linked list @Pre listPtr points to an element of a list. @Post 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 }

38 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

39 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

40 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

41 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

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

43 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

44 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

45 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

46 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

47 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

48 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;

49 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

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

51 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)

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

53 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

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

55 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

56 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)

57 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

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

59 Combinations(4, 3)

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

61 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

62 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.

63 // 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?

64 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

65 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

66 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

67 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

68 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

69 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

70 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.

71 // USES TAIL RECURSION bool ValueInList ( ListType list, int value, int startIndex ) /** Searches list for value between positions startIndex and list.length-1 @Pre list.info[ startIndex ].. list.info[ list.length - 1 ] contain values to be searched @Post 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 ); }

72 // ITERATIVE SOLUTION bool ValueInList ( ListType list, int value, int startIndex ) /** Searches list for value between positions startIndex and list.length-1 @Pre list.info[ startIndex ].. list.info[ list.length - 1 ] contain values to be searched @Post 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; }

73 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

74 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


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

Similar presentations


Ads by Google