Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 10 Recursion.

Similar presentations


Presentation on theme: "Chapter 10 Recursion."— Presentation transcript:

1 Chapter 10 Recursion

2 Outline 10.1 THE NATURE OF RECURSION 10.2 TRACING A RECURSIVE FUNCTION
10.3 RECURSIVE MATHMETICAL FUNCTIONS 10.4 RECURSIVE FUNCTIONS WITH ARRAY AND STRING PARAMETERS CASE STUDY FINDING CAPITAL LETTERS IN A STRING RECURSIVE SELECTION SORT 10.5 PROBLEM SOLVING WITH RECURSION OPERATIONS ON SETS 10.6 A CLASSIC CASE STUDY IN RECURSION TOWERS OF HANOI 10.7 COMMON PROGRAMMING ERRORS Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

3 10.1 THE NATURE OF RECURSION
Recursive function Function that calls itself or that is part of a cycle in the sequence of function calls Simple case Problem case for which a straightforward solution is known Recursive solution characteristics One or more simple cases of the problem have a straightforward, nonrecursive solution The other cases can be redefined in terms of problems that are closer to the simple cases By applying this redefinition process every time the recursive function is called, eventually the problem is reduced entirely to simple cases, which are relatively easy to solve Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

4 redefine the problem using recursion
Recursive Algorithm if this is a simple case solve it else redefine the problem using recursion Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

5 The idea Recursion is all about breaking a big problem into smaller occurrences of that same problem. Each person can solve a small part of the problem. What is a small version of the problem that would be easy to answer? What information from a neighbor might help me?

6 Recursive algorithm Number of people behind me:
If there is someone behind me, ask him/her how many people are behind him/her. When they respond with a value N, then I will answer N + 1. If there is nobody behind me, I will answer 0.

7 Figure 10.1 Splitting a Problem into Smaller Problems
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

8 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

9 來源 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

10 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.
來源 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

11 來源http://upload. wikimedia
來源 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

12 The simplest case is reached when the condition n==1 is true.
EXAMPLE 10.1 Figure 10.2 implements multiplication as the recursive C function multiply that returns the product m x n of its two arguments. The body of function multiply implements the general form of a recursive algorithm. The simplest case is reached when the condition n==1 is true. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

13 Figure 10.2 Recursive Function multiply
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

14 Tracing a recursive function that returns a value
Activation frame Representation of one call to a function Figure 10.5 shows three calls to function multiply. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

15 Figure 10.5 Trace of Function multiply
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

16 Fractals

17 EXAMPLE 10.2 Develop a function to count the number of times a particular character appears in a string. Figure 10.3 shows thought process that fits into our generic else clause. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

18 Figure 10.3 Thought Process of Recursive Algorithm Developer
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

19 Figure 10.4 Recursive Function to Count a Character in a String
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

20 10.2 TRACING A RECURSIVE FUNCTION
Two types of tracing the execution of a recursive function Tracing a recursive function that returns a value Tracing a void function that is recursive Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

21 Tracing a void function that is recursive
Function reverse_input_words in Fig.10.6 is a recursive module that takes n words of input and prints them in reverse order. Terminating condition A condition that is true when a recursive algorithm is processing a simple case Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

22 Factorial Function function Factorial returnsa Num(n isoftype in Num)
// Calculates n factorial, n! // Precondition: n is a non-negative // integer if (n = 0) then Factorial returns 1 else Factorial returns n * Factorial(n-1) endif endfunction //Factorial

23 if (0 = 0) then Fact returns 1 else Fact returns 1 endif endfunction //Fact if (1 = 0) then Fact returns 1 else Fact returns 1 * Fact(0) endif endfunction //Fact if (2 = 0) then Fact returns 1 else Fact returns 2 * Fact(1) endif endfunction //Fact if (3 = 0) then Fact returns 1 else Fact returns 3 * Fact(2) endif endfunction //Fact algorithm Test ans <- Fact(3) endalgorithm

24 Tracing Details 1. Actual parameters stored on the stack
5. Return value and release stack frame 3. Create a new Stack Frame function Fact returnsa Num (2) if (2 = 0) then Fact returns 1 else Fact returns 2 * Fact(1) endif endfunction //Fact 4. Unfinished Business 2. Recursive call to Fact

25 Activation Stack for Factorial
Call the function: answer <- Fact(5) Main Algorithm: Unfinished: answer <- Fact (5)

26 Activation Stack for Factorial
Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

27 Activation Stack for Factorial
Fact. 2nd: N=4, Unfinished: 4*Fact(3) Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

28 Activation Stack for Factorial
Fact. 3rd: N=3, Unfinished: 3*Fact(2) Fact. 2nd: N=4, Unfinished: 4*Fact(3) Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

29 Activation Stack for Factorial
Fact. 4th: N=2, Unfinished: 2*Fact(1) Fact. 3rd: N=3, Unfinished: 3*Fact(2) Fact. 2nd: N=4, Unfinished: 4*Fact(3) Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

30 Activation Stack for Factorial
Fact. 5th: N=1, Unfinished: 1*Fact(0) Fact. 4th: N=2, Unfinished: 2*Fact(1) Fact. 3rd: N=3, Unfinished: 3*Fact(2) Fact. 2nd: N=4, Unfinished: 4*Fact(3) Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

31 Activation Stack for Factorial
Fact. 6th: N=0, Finished: returns 1 Fact. 5th: N=1, Unfinished: 1*Fact(0) Fact. 4th: N=2, Unfinished: 2*Fact(1) Fact. 3rd: N=3, Unfinished: 3*Fact(2) Fact. 2nd: N=4, Unfinished: 4*Fact(3) Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

32 Activation Stack for Factorial
Fact. 5th: N=1, Finished: returns 1*1 Fact. 4th: N=2, Unfinished: 2*Fact(1) Fact. 3rd: N=3, Unfinished: 3*Fact(2) Fact. 2nd: N=4, Unfinished: 4*Fact(3) Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

33 Activation Stack for Factorial
Fact. 4th: N=2, Finished: returns 2*1 Fact. 3rd: N=3, Unfinished: 3*Fact(2) Fact. 2nd: N=4, Unfinished: 4*Fact(3) Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

34 Activation Stack for Factorial
Fact. 3rd: N=3, Finished: returns 3*2 Fact. 2nd: N=4, Unfinished: 4*Fact(3) Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

35 Activation Stack for Factorial
Fact. 2nd: N=4, Finished: returns 4*6 Fact. 1st: N=5, Unfinished: 5*Fact(4) Main Algorithm: Unfinished: answer <- Fact (5)

36 Activation Stack for Factorial
Fact. 1st: N=5, Finished: returns 5*24 Main Algorithm: Unfinished: answer <- Fact (5)

37 Activation Stack for Factorial
Main Algorithm: Finished: answer <- 120

38 Could be written as a function
LB Exponentiation baseexponent e.g. 53 Could be written as a function Power(base, exp)

39 Can we write it recursively?
LB Can we write it recursively? be = b * b(e-1) What’s the limiting case? When e = 0 we have b0 which always equals? 1

40 Another Recursive Function
function Power returnsa Num (base, exp isoftype in Num) // Computes the value of BaseExp // Pre: exp is a non-negative integer if (exp = 0) then Power returns 1 else Power returns base * Power(base, exp-1) endif endfunction //Power

41 Activations Stack Example
Function Power returnsa Num (base, exp isoftype in Num) //Computes the value of BaseExp //Preconditions: exp is a non-negative integer if(exp = 0 ) then Power returns 1 else Power returns (base * Power(base, exp – 1)) endif endfunction //Power Power base = 3 exp = Finished: 1 1 Power base = 3 exp = *Power(3,0) 1 3 Power base = 3 exp = *Power(3,1) 3 9 Power base = 3 exp = *Power(3,2) 9 27 Power base = 3 exp = *Power(3,3) 27 81 Algo: total <- Power(3,4) Total <- 81

42 Bunnies? LB The Time: 13th Century The Place: Italy The Man: Fibonacci
The Problem: We start with a pair of newborn rabbits. At the end of the 2nd month, and each month thereafter the female gives birth to a new pair of rabbits: one male and one female. The babies mature at the same rate as the parents and begin to produce offspring on the same schedule. So how many rabbits do we have at the end of one year?

43 LB = 1 pair bunnies (m/f)

44 A More Complex Recursive Function
Fibonacci Number Sequence if n = 1, then Fib(n) = 1 if n = 2, then Fib(n) = 1 if n > 2, then Fib(n) = Fib(n-2) + Fib(n-1) Numbers in the series: 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

45 Fibonacci Sequence Function
function Fib returnsa Num (n iot in Num) // Calculates the nth Fibonacci number // Precondition: N is a positive integer if ((n = 1) OR (n = 2)) then Fib returns 1 else Fib returns Fib(n-2) + Fib(n-1) endif endfunction //Fibonacci

46 Fibonacci sequence Definition of the Fibonacci sequence
Non-recursive: Recursive: F(n) = F(n-1) + F(n-2) or: F(n+1) = F(n) + F(n-1) Must always specify base case(s)! F(1) = 1, F(2) = 1 Note that some will use F(0) = 1, F(1) = 1

47 Fibonacci sequence in Java
long Fibonacci (int n) { if ( (n == 1) || (n == 2) ) return 1; else return Fibonacci (n-1) + Fibonacci (n-2); } long Fibonacci2 (int n) { return (long) ((Math.pow((1.0+Math.sqrt(5.0)),n)- Math.pow((1.0-Math.sqrt(5.0)),n)) / (Math.sqrt(5) * Math.pow(2,n)));

48 Tracing with Multiple Recursive Calls
Main Algorithm: answer <- Fib(5)

49 Tracing with Multiple Recursive Calls
Fib(5): Fib returns Fib(3) + Fib(4) Main Algorithm: answer <- Fib(5)

50 Tracing with Multiple Recursive Calls
Fib(3): Fib returns Fib(1) + Fib(2) Fib(5): Fib returns Fib(3) + Fib(4) Main Algorithm: answer <- Fib(5)

51 Tracing with Multiple Recursive Calls
Fib(1): Fib returns 1 Fib(3): Fib returns Fib(1) + Fib(2) Fib(5): Fib returns Fib(3) + Fib(4) Main Algorithm: answer <- Fib(5)

52 Tracing with Multiple Recursive Calls
Fib(3): Fib returns 1 + Fib(2) Fib(5): Fib returns Fib(3) + Fib(4) Main Algorithm: answer <- Fib(5)

53 Tracing with Multiple Recursive Calls
Fib(2): Fib returns 1 Fib(3): Fib returns 1 + Fib(2) Fib(5): Fib returns Fib(3) + Fib(4) Main Algorithm: answer <- Fib(5)

54 Tracing with Multiple Recursive Calls
Fib(3): Fib returns 1 + 1 Fib(5): Fib returns Fib(3) + Fib(4) Main Algorithm: answer <- Fib(5)

55 Tracing with Multiple Recursive Calls
Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

56 Tracing with Multiple Recursive Calls
Fib(4): Fib returns Fib(2) + Fib(3) Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

57 Tracing with Multiple Recursive Calls
Fib(2): Fib returns 1 Fib(4): Fib returns Fib(2) + Fib(3) Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

58 Tracing with Multiple Recursive Calls
Fib(4): Fib returns 1 + Fib(3) Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

59 Tracing with Multiple Recursive Calls
Fib(3): Fib returns Fib(1) + Fib(2) Fib(4): Fib returns 1 + Fib(3) Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

60 Tracing with Multiple Recursive Calls
Fib(1): Fib returns 1 Fib(3): Fib returns Fib(1) + Fib(2) Fib(4): Fib returns 1 + Fib(3) Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

61 Tracing with Multiple Recursive Calls
Fib(3): Fib returns 1 + Fib(2) Fib(4): Fib returns 1 + Fib(3) Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

62 Tracing with Multiple Recursive Calls
Fib(2): Fib returns 1 Fib(3): Fib returns 1 + Fib(2) Fib(4): Fib returns 1 + Fib(3) Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

63 Tracing with Multiple Recursive Calls
Fib(3): Fib returns 1 + 1 Fib(4): Fib returns 1 + Fib(3) Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

64 Tracing with Multiple Recursive Calls
Fib(4): Fib returns 1 + 2 Fib(5): Fib returns 2 + Fib(4) Main Algorithm: answer <- Fib(5)

65 Tracing with Multiple Recursive Calls
Fib(5): Fib returns 2 + 3 Main Algorithm: answer <- Fib(5)

66 Tracing with Multiple Recursive Calls
Main Algorithm: answer <- 5

67 Figure 10.6 Function reverse_input_words
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

68 Figure 10.7 Trace of reverse_input_words(3) When the Words Entered are "bits" "and" "bytes"
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

69 Figure 10.8 Sequence of Events for Trace of reverse_input_words(3)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

70 Parameter And Local Variable Stacks (1/5)
C uses the stack data structure to keep track of the values of n and word at any given point. After first call to reverse_input_words n word 3 ? Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

71 Parameter And Local Variable Stacks (2/5)
Before the second call to reverse_input_words n word 3 bits After second call to reverse_input_words n word 2 ? 3 bits Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

72 Parameter And Local Variable Stacks (3/5)
Before the third call to reverse_input_words n word 2 and 3 bits After third call to reverse_input_words n word 1 ? 2 and 3 bits Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

73 Parameter And Local Variable Stacks (4/5)
During this execution of the function, the word “bytes” is scanned and stored in word, and “bytes” is echo printed immediately because n is 1 (a simple case) n word 1 bytes 2 and 3 bits The function return pops both stacks After first return n word 2 and 3 bits Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

74 Parameter And Local Variable Stacks (5/5)
Because control is returned to a printf call, the value of word at the top of the stack is then displayed. Another return occurs, poping the stacks again. After second return n word 3 bits Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

75 Implementation of Parameter Stacks in C
System stack Area of memory where parameters and local variables are allocated when a function is called and deallocated when the function returns When and how to trace recursive functions During algorithm development, it is best to trace a specific case simply by trusting any recursive call to return a correct value based on the function purpose. Figure 10.9 shows a self-tracing version of function multiply as well as output generated by the call. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

76 Figure Recursive Function multiply with Print Statements to Create Trace and Output from multiply(8, 3) Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

77 Figure Recursive Function multiply with Print Statements to Create Trace and Output from multiply(8, 3) (cont’d) Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

78 10.3 RECURSIVE MATHMETICAL FUNCTIONS
Many mathmatical functions can be defined recursively. For example The factorial of a number n (n!) Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

79 Figure 10.10 Recursive factorial Function
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

80 Figure 10.11 shows the trace of fact=factorial(3)
EXAMPLE 10.4 Figure shows the trace of fact=factorial(3) Figure uses iterative version to solve the factorial of the number n Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

81 Figure 10.11 Trace of fact = factorial(3);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

82 Figure 10.12 Iterative Function factorial
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

83 The Fibonacci sequence is defined as
EXAMPLE 10.5 The Fibonacci numbers are a sequence of numbers that have many varied uses. The Fibonacci sequence is defined as Fibonacci1 is1 Fibonacci2 is 1 Fibonaccin is Fibonaccin-2 +Fibonaccin-1, for n>2 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

84 Figure 10.13 Recursive Function fibonacci
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

85 Euclid’s algorithm for finding the gcd can be defined recursively
EXAMPLE 10.6 Euclid’s algorithm for finding the gcd can be defined recursively gcd(m,n) is n if n divides m evently gcd(m,n) is gcd(n, remainder of m divided by n) otherwise Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

86 Figure 10.14 Program Using Recursive Function gcd
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

87 Figure 10.14 Program Using Recursive Function gcd (cont’d)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

88 10.4 RECURSIVE FUNCTIONS WITH ARRAY AND STRING PARAMETERS CASE STUDY: FINDING CAPITAL LETTERS IN A STRING(1/4) Step 1: Problem Form a string containing all the capital letters found in another string. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

89 CASE STUDY: FINDING CAPITAL LETTERS IN A STRING(2/4)
Step 2: Analysis Problem Input char *str Problem Output char *caps Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

90 CASE STUDY: FINDING CAPITAL LETTERS IN A STRING(3/4)
Step 3: Design Algorithm 1. if str is the empty string 2. Store empty string in caps (a string with no letters certainly has no caps) else 3. if initial letter of str is a capital letter 4. Store in caps this letter and the capital letters from the rest of str 5. Store in caps the capital letters from the rest of str Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

91 CASE STUDY: FINDING CAPITAL LETTERS IN A STRING(4/4)
Step 4: Implementation (Figure10.15) Step 5: Testing (Figure 10.16、Figure 10.17) Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

92 Figure 10.15 Recursive Function to Extract Capital Letters from a String
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

93 Figure 10.16 Trace of Call to Recursive Function find_caps
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

94 Figure 10.17 Sequence of Events for Trace of Call to find_caps from printf Statements
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

95 CASE STUDY RECURSIVE SELECTION SORT(1/4)
Step 1: Problem Sort an array in ascending order using a selection sort. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

96 CASE STUDY RECURSIVE SELECTION SORT(2/4)
Step 2: Analysis (Figure 10.18) Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

97 Figure 10.18 Trace of Selection Sort
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

98 CASE STUDY RECURSIVE SELECTION SORT(3/4)
Step 3: Design Recursive algorithm for selection sort 1. if n is 1 2. The array is sorted. else 3. Place the largest array value in last array element 4. Sort the subarray which excludes the last array element (array[0]..array[n-2]) Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

99 CASE STUDY RECURSIVE SELECTION SORT(4/4)
Step 4: Implementation (Figure10.19) Step 5: Testing Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

100 Figure 10.19 Recursive Selection Sort
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

101 Figure 10.19 Recursive Selection Sort (cont’d)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

102 10.5 PROBLEM SOLVING WITH RECURSION CASE STUDY OPERATIONS ON SETS(1/4)
Step 1: Problem Develop a group of functions to perform the E (is an element of), (is a subset of) and ∪ (union) operations on sets of characters. Also develop functions to check that a certain set is valid (that is, that it contains no duplicate characters), to check for the empty set, and to print a set in standard set notation. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

103 CASE STUDY OPERATIONS ON SETS(2/4)
Step 2: Analysis Character strings provide a fairly natural representation of sets of characters. Like sets, strings can be of varying sizes and can be empty. If a character array that is to hold a set is declared to have one more than the number of characters in the universal set (to allow room for the null character), then set operations should never produce a string that will overflow the array. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

104 CASE STUDY OPERATIONS ON SETS(3/4)
Step 3: Design Algorithm for is_empty(set) 1. Is initial character ‘\0’ ? Algorithm for is_element(ele, set) if is_empty(set) 2. Answer is false else if initial character of set matches ele 3. Answer is true else 4. Answer depends on whether ele is in the rest of set Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

105 Step 3: Design (cont’s) Algorithm for is_set(set)
if is_empty(set) 2. Answer is true else if is_element(initial set character, rest of set) 3. Answer is false else 4. Answer depends on whether rest of set is valid set Algorithm for is_subset(sub, set) if is_empty(sub) else if initial character of sub is not an element of set 4. Answer depends on whether rest of sub is a subset of set Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

106 Step 3: Design (cont’s) Algorithm for union of set1 and set2
if is_empty(set1) 2. Result is set2 else if initial character of sset1 is also an element of set2 3. Result is union of the rest of set1 with set2 else 4. Result includes initial character of set1 and the union of the rest of set1 with set2 Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

107 Step 3: Design (cont’s) Algorithm for print_set(set)
Output a { . if set is not empty, print elements seperated by commas. Output a } . Algorithm for print_with_commas(set) If set has exactly one element 2. Print it else 3. Print initial element and a comma 4. print_with_commas the rest of set Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

108 CASE STUDY OPERATIONS ON SETS(4/4)
Step 4: Implementation (Figure10.20) Step 5: Testing Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

109 Figure 10.20 Recursive Set Operations on Sets Represented as Character Strings
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

110 Figure 10.20 Recursive Set Operations on Sets Represented as Character Strings (cont’d)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

111 Figure 10.20 Recursive Set Operations on Sets Represented as Character Strings (cont’d)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

112 Figure 10.20 Recursive Set Operations on Sets Represented as Character Strings (cont’d)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

113 Figure 10.20 Recursive Set Operations on Sets Represented as Character Strings (cont’d)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

114 Figure 10.20 Recursive Set Operations on Sets Represented as Character Strings (cont’d)
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

115 10.6 A CLASSIC CASE STUDY IN RECURSION TOWERS OF HANOI (1/)
Step 1: Problem Move n disks from peg A to peg C using peg B as needed. The following conditions apply 1. Only one disk at a time may be moved, and this disk must be the top disk on a peg 2. A larger disk can never be placed on top of a smaller disk Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

116 TOWERS OF HANOI (2/) Step 2: Analysis Problem inputs Problem output
int n char from_peg char to_peg char aux_peg Problem output A list of individual disk moves Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

117 Figure Towers of Hanoi Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

118 Figure 10.22 Towers of Hanoi After Steps 1 and 2
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

119 Figure 10.23 Towers of Hanoi After Steps 1, 2, 3.1, and 3.2
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

120 TOWERS OF HANOI (3/) Step 3: Design Algorithm if n is 1 then
2. Move disk 1 from the from peg to the to peg else 3. Move n-1 disks from the from peg to the auxiliary peg using the to peg 4. Move disk n from the from peg to the to peg 5. Move n-1 disks from the auxiliary peg to the to peg using the from peg Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

121 Step 4: Implementation (Figure10.24) Step 5: Testing
TOWERS OF HANOI (4/4) Step 4: Implementation (Figure10.24) Step 5: Testing Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

122 Figure 10.24 Recursive Function tower
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

123 Figure 10.25 Trace of tower ('A', 'C', 'B', 3);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

124 Figure 10.26 Output Generated by tower ('A', 'C', 'B', 3);
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

125 Comparison of Iterative and Recursive Functions
Requires more time and space because of extra function calls Is much easier to read and understand To researchers developing solutions to the complex problems that are at the frontiers of their research areas, the benefits gained from increased clarity far outweigh the extra cost in time and memory of running a recursive program Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

126 10.7 COMMON PROGRAMMING ERRORS
A recursive function may not be terminate properly. A run-time error message noting stack overflow or an access violation is an indicator that a recursive function is not terminating Be aware that it is critical that every path through a nonvoid function leads to a return statement The recopying of large arrays or other data structures can quickly consume all available memory Introduce a nonrecursive function to handle preliminaries and call the recursive function when there is error checking Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

127 Chapter Review A recursive function either calls itself or initiates a sequence of function calls in which it may be called again Designing a recursive solution involves identifying simple cases that have straightforward solutions and then redefining more complex cases in terms of problems that are closer to simple cases Recursive functions depend on the fact that for each cal to a function, space is allocated on the stack for the function’s parameters and local variables Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

128 Question? Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

129 Programming Projects 1 Develop a program to count pixels (picture elements) belonging to an object in a photograph. The data are in a two-dimensional grid of cells, each of which may be empty (value 0) or filled (value 1). The filled cells that are connected form a blob (an object). Figure shows a grid with three blobs. Include in your program a function blob_check that takes as parameters the grid and the x-y coordinates of a cell and returns as its value the number of cells in the blob to which the indicated cell belongs. Copyright ©2004 Pearson Addison-Wesley. All rights reserved.

130 Figure 10.27 Grid with Three Blobs
Copyright ©2004 Pearson Addison-Wesley. All rights reserved.


Download ppt "Chapter 10 Recursion."

Similar presentations


Ads by Google