Presentation is loading. Please wait.

Presentation is loading. Please wait.

Recursion Chapter 2 Objectives Upon completion you will be able to:

Similar presentations


Presentation on theme: "Recursion Chapter 2 Objectives Upon completion you will be able to:"— Presentation transcript:

1 Recursion Chapter 2 Objectives Upon completion you will be able to:
Explain the difference between iteration and recursion Design a recursive algorithm Determine when an recursion is an appropriate solution Write simple recursive functions Data Structures: A Pseudocode Approach with C

2 2-1 Factorial - A Case Study
We begin the discussion of recursion with a case study and use it to define the concept. This section also presents an iterative and a recursive solution to the factorial algorithm. Recursive Defined Recursive Solution Data Structures: A Pseudocode Approach with C

3 Introduction There are 2 approaches to writing repetitive algorithms: iteration & recursion Recursion is a repetitive process in which an algorithm calls itself some older languages do not support recursion: COBOL Data Structures: A Pseudocode Approach with C

4 2-1 Factorial – A case study
The factorial of a number is the product of the integral values from 1 to the number example: Factorial(4) = 4 x 3 x 2 x 1 = 24 Data Structures: A Pseudocode Approach with C

5 Data Structures: A Pseudocode Approach with C

6 Data Structures: A Pseudocode Approach with C

7 Data Structures: A Pseudocode Approach with C

8 Recursion Defined (2) From Figure 2-2, it looks like the recursive calculation is much longer and more difficult Why would we want to use the recursive method? The reasons are the recursive calculation looks more difficult when using paper and pencil, but is often a much easier and a more elegant solution when we use computers conceptual simplicity to the creator and the reader Data Structures: A Pseudocode Approach with C

9 Data Structures: A Pseudocode Approach with C

10 Data Structures: A Pseudocode Approach with C

11 Data Structures: A Pseudocode Approach with C

12 How recursive works When a prg calls a subroutine, the current module suspends processing and the called subroutine takes over control of the prg When a subroutine completes its processing and returns to the module that called it, the module wakes up and continues its processing Data Structures: A Pseudocode Approach with C

13 How recursive works (2) call by value, call by reference,
all local data in the calling module are unchanged the parameter list must not be changed call by reference, parameter list can be changed Data Structures: A Pseudocode Approach with C

14 Figure 2-5: Call and return
Data Structures: A Pseudocode Approach with C

15 StackFrame A stackframe contains 4 different elements
the parameters to be processed by the called alg the local variables in the calling alg the return statement in the calling alg the variable that is to receive the return value (if any) Data Structures: A Pseudocode Approach with C

16 Algorithm: Recursive power algorithm
algorithm power ( val base <integer>, val exp <integer> ) This algorithm computes the value of a number, base, raised to the power of an exponent ,exp. Pre base is the number to be raised exp is the exponent Post value of base**exp computed Return value of base**exp returned 1 if (exp equal 0) 1 return (1) 2 else 1 return (base * power (base , exp - 1)) end power Data Structures: A Pseudocode Approach with C

17 Figure 2-6: Stackframes for power (5, 2)
Data Structures: A Pseudocode Approach with C

18 2-2 Designing Recursive Algorithms
In this section we present an analytical approach to designing recursive algorithms. We also discuss algorithm designs that are not well suited to recursion. The Design Methodology Limitation of Recusion Design Implemenation Data Structures: A Pseudocode Approach with C

19 The Design Methodology
there are 2 elements in recursive algs Solves one part of the problem alg 2-2, statement 1.1 reduces the size of the problem alg 2-2, statement 2.1 Data Structures: A Pseudocode Approach with C

20 The Design Methodology (2)
The statement that “solves” the problem is know as the base case Every recursive alg must have a base case The rest of the alg is known as the general case the general case contains the logic needed to reduce the size of the problem Data Structures: A Pseudocode Approach with C

21 The rules for designing a recursive algs
step 1: determine the base case step 2: determine the general case step 3: combine the base case and general case into an algorithm in the 3rd step, each call must reduce the size of the problem and move it toward the base case the base case,when reached, must terminate without a call to the recursive alg, that is it must execute a return Data Structures: A Pseudocode Approach with C

22 Limitations of Recursion
Recursion works best when the alg uses a data structure that naturally supports recursion or the alg is naturally suited to recursion Examples: 1. data structure: - trees are naturally recursive structure and recursion works well with them 2. algorithm: - the binary search alg lends itself to a natural recursive alg as does the Towers of Hanoi Data Structures: A Pseudocode Approach with C

23 Limitations of Recursion (2)
Not all looping algs can or should be implemented with recursion Recursive solutions involve overhead when a call is made, it takes time to build a stackframe and push it into a stack conversely, when a return is executed, the stackframe must be popped from the stack and the local variables reset to their previous values A recursive alg generally runs slower than its nonrecursive implementation Data Structures: A Pseudocode Approach with C

24 Limitations of Recursion (3)
should not use recursion if the answer to any of the following questions is “no” is the alg or data structure naturally suited to recursion? is the recursive solution shorter and more understandable? does the recursive solution run in acceptable time and space limits? Data Structures: A Pseudocode Approach with C

25 Data Structures: A Pseudocode Approach with C

26 Data Structures: A Pseudocode Approach with C

27 Design Implementation-a linked list
suppose we have a linked list as below Figure 2-7: A linked list we need to print the list in reverse, but do not have reverse pointers the easy way to do this is to write a recursive alg Data Structures: A Pseudocode Approach with C

28 Design Implementation-a linked list (2)
to print the list in reverse, we must traverse it to find the last node the base case is that the end of the list is found the general case is to find the next node Data Structures: A Pseudocode Approach with C

29 Figure 2-8:Print linked list in reverse
Data Structures: A Pseudocode Approach with C

30 Algorithm 2-4 Print linked-list reverse
algorithm printReverse( val list <pointer to node>) Print singly linked list in reverse Pre list has been built Post list printed in reverse 1 if (null list) 1 return 2 printReverse (list - >next) Have reached end of list : print nodes 3 print (list ->data) 4 return end printReverse Data Structures: A Pseudocode Approach with C

31 Algorithm 2-4 Analysis consider 3 questions developed in limitations of recursion is the alg or data structure naturally suited to recursion? - a linear list is not a naturally recursive structure - the alg is not naturally suited to recursion (it is not one of the logarithemic algs) Data Structures: A Pseudocode Approach with C

32 Algorithm 2-4 Analysis (2)
is the recursive solution shorter and more understandable? - yes and the recursive alg is shorter and easier to understand Data Structures: A Pseudocode Approach with C

33 Algorithm 2-4 Analysis (3)
does the recursive solution run in acceptable time and space limits? - the number of iterations in the traversal of a linear list can become quite large. - the alg has a linear efficiency: O(n) - it is not a good candidate for recursion Data Structures: A Pseudocode Approach with C

34 Algorithm 2-4 Analysis (4)
The conclusion of the answer in this problem is “no” since 2 of the 3 questions is no therefore, we should not use the recursion in this problem, although we can successfully write the alg recursively Data Structures: A Pseudocode Approach with C

35 2-3 Recursive Examples Four recursive programs are developed and analyzed. Only one, the Towers of Hanoi, turns out to be a good application for recursion. Greatest Common Divisor (GCD) Fiboncci Numbers Prefix to Postfix Conversion The Towers of Honoi Data Structures: A Pseudocode Approach with C Slide 05

36 Data Structures: A Pseudocode Approach with C

37 Data Structures: A Pseudocode Approach with C

38 Data Structures: A Pseudocode Approach with C

39 Data Structures: A Pseudocode Approach with C

40 Fibonacci Numbers Named after an Italian mathematician (early 13th century), Leonardo Fibonacci Fibonacci numbers are a series in which each number is the sum of the previous two numbers example: 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 Data Structures: A Pseudocode Approach with C

41 Data Structures: A Pseudocode Approach with C

42 Algorithm Fibonacci number
This program prints out a Fibonacci series. 1 print (This program prints a Fibonacci series.) 2 print (How many numbers do you want ?) 3 read (seriesSize) 4 if (seriesSize < 2) 1 seriesSize = 2 5 print (First seriesSize Fibonacci numbers are : ) 6 looper = 0 Data Structures: A Pseudocode Approach with C

43 Algorithm Fibonacci number (2)
7 loop (looper < seriesSize ) Get next Fibonacce number 1 nextFib = fib(looper ) 2 print (bextFib) 3 looper = loober + 1 end Fibonacci Data Structures: A Pseudocode Approach with C

44 Generalize the Fibonacci series
to start the series, we need to know the first two numbers: 0 and 1 these two numbers are recognized as the base case Given : Fibonacci (0) = 0 Fibonacci(1) = 1 Then Fibonacci(n) = Fibonacci (n-1) + Fibonacci(n-2) Data Structures: A Pseudocode Approach with C

45 Figure 2-9: Fibonacci numbers
Data Structures: A Pseudocode Approach with C

46 Algorithm 2-6 Recursive Fibonacci
algorithm fib (val num <interger>) Calculates the nth Fibonacci number . Pre num identefied the ordinal of the Fibonacci number Post returns the nth Fibonacci number 1 if (num is 0 OR num is 1 ) Base Case 1 return num 2 return (fib (num - 1) + fib (num - 2) end fib Data Structures: A Pseudocode Approach with C

47 Data Structures: A Pseudocode Approach with C

48 (Continued) Data Structures: A Pseudocode Approach with C

49 Data Structures: A Pseudocode Approach with C

50 Data Structures: A Pseudocode Approach with C

51 Prefix to Postfix Conversion
Arithmetic expression can be represented in 3 formats: Infix : A + B Postfix : + A B Prefix : A B + Data Structures: A Pseudocode Approach with C

52 Data Structures: A Pseudocode Approach with C

53 Data Structures: A Pseudocode Approach with C

54 Data Structures: A Pseudocode Approach with C

55 Data Structures: A Pseudocode Approach with C

56 Data Structures: A Pseudocode Approach with C

57 Data Structures: A Pseudocode Approach with C

58 Data Structures: A Pseudocode Approach with C

59 Data Structures: A Pseudocode Approach with C

60 Data Structures: A Pseudocode Approach with C

61 Data Structures: A Pseudocode Approach with C

62 The Towers of Hanoi it is a classic recursion problem:
relatively easy to follow is efficient uses no complex data structures Where the problem come from? from the legend, the monks knew how to predict when the world would end they had a set of 3 diamond needles stacked o the first needle were 64 gold disks of decreasing size the monks move one disk to another needle each hour Data Structures: A Pseudocode Approach with C

63 Rules The moves subject to the following rules
only one disk could be move at a time a larger disk must never be stacked above a smaller one one and only one auxiliary needle could be used for the intermediate storage of disks Data Structures: A Pseudocode Approach with C

64 The Towers of Hanoi (2) The legend said when all 64 disks has been transferred to the destination needle, the stars would be extinguished and the world would end how many moves we need? = 264 – 1 moves Data Structures: A Pseudocode Approach with C

65 Data Structures: A Pseudocode Approach with C

66 Data Structures: A Pseudocode Approach with C

67 The Towers of Hanoi (3) This problem is interesting for 2 reasons
the recursive solution is much easier to code than the iterative solution would be its solution pattern is different from the simple examples note that after each base case, we return to a decomposition of the general case for several steps the problem is divided into several subproblems, each of which has base case , moving one disk Data Structures: A Pseudocode Approach with C

68 Recursive Towers of Hanoi
To find the pattern of moving, let start from 1 disks to 3 disks Case 1: move one disk from source to destination needle Case 2: move one disk to auxiliary needle move one disk to destination needle move one disk from auxiliary to destination needle Data Structures: A Pseudocode Approach with C

69 Recursive Towers of Hanoi (2)
Case 3: move one disk to auxiliary needle move one disk to destination needle move one disk from auxiliary to destination needle Data Structures: A Pseudocode Approach with C

70 Data Structures: A Pseudocode Approach with C

71 (Continued) Data Structures: A Pseudocode Approach with C

72 Data Structures: A Pseudocode Approach with C

73 Data Structures: A Pseudocode Approach with C

74 Data Structures: A Pseudocode Approach with C

75 Data Structures: A Pseudocode Approach with C

76 Data Structures: A Pseudocode Approach with C

77 Data Structures: A Pseudocode Approach with C

78 Data Structures: A Pseudocode Approach with C

79 Data Structures: A Pseudocode Approach with C

80 Data Structures: A Pseudocode Approach with C


Download ppt "Recursion Chapter 2 Objectives Upon completion you will be able to:"

Similar presentations


Ads by Google