Download presentation
Presentation is loading. Please wait.
Published byRodger Lyons Modified over 9 years ago
1
Pei Zheng, Michigan State University 1 Chapter 8 Recursion
2
2 Objective To learn: What is recursion? Proof by induction Basic recursion Numerical Applications Divide and Conquer
3
3 Recursive Function Call A recursion function is a function that either directly or indirectly makes a call to itself. But, we need to avoid making an infinite sequence of function calls (infinite recursion). A recursive solution to a problem must be written carefully The idea is for each successive recursive call to bring you one step closer to a situation in which the problem can easily be solved This easily solved situation is called the base case Each recursive algorithm must have at least one base case, as well as a general (recursive) case
4
4 Mathematical Induction To prove Let p(n) denote the statement involving the integer variable n. The Principle of Mathematical Induction states: If p(1) is true and, for some integer K >=1, p(k+1) is true whenever p(k) is true then p(n) is true for all n>=1.
5
5 A recursive definition int s (int n) { if (n ==1) return 1; else return s(n-1) + n; }
6
6 Printing number in 10 Base void printDecimal (int n) { if (n>=10) { printDecimal(n/10); } cout.put(‘0’+n%10); }
7
7 Printing number in Any Base const string DIGIT_TABLE = "0123456789abcdef"; const int MAX_BASE = DIGIT_TABLE.length( ); void printIntRec( int n, int base ) { if( n >= base ) { printIntRec( n / base, base ); } cout << DIGIT_TABLE[ n % base ]; }
8
8 General format for Many Recursive Functions if (some easily-solved condition) // base case solution statement else // general case recursive function call
9
9 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 for the function call
10
10 Stack Activation Frames The activation record contains the return address for this function call, and also the parameters, and local variables, and space for 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
11
11 FCTVAL ? result ? b 2 a 5 Return Address 100 Run-Time Stack Activation Records x = Func(5, 2); // original call at instruction 100 original call at instruction 100 pushes on this record for Func(5,2)
12
12 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) Run-Time Stack Activation Records x = Func(5, 2); // original call at instruction 100
13
13 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 x = Func(5, 2); // original call at instruction 100
14
14 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,0) is popped first with its FCTVAL Run-Time Stack Activation Records x = Func(5, 2); // original call at instruction 100 record for Func(5,2) record for Func(5,1)
15
15 record for Func(5,2) record for Func(5,1) is popped next with its FCTVAL Run-Time Stack Activation Records x = Func(5, 2); // original call at instruction 100 FCTVAL 5 result 5+Func(5,0) = 5+ 0 b 1 a 5 Return Address 100 FCTVAL ? result 5+Func(5,1) = ? b 2 a 5 Return Address 100
16
16 FCTVAL 10 result 5+Func(5,1) = 5+5 b 2 a 5 Return Address 100 record for Func(5,2) is popped last with its FCTVAL Run-Time Stack Activation Records x = Func(5, 2); // original call at instruction 100
17
17 Too much recursion Can Be Dangerous … Fibonacci numbers. Long fib (int n) { If (n <=1) return n; Else return fib(n-1) + fib(n-2); } This definition will lead to exponential running time.
18
18 Tree Tree is a fundamental structure in computer science. Recursive definition: A tree is a root and zero or more nonempty subtrees. Nonrecursive definition: A connected graph without loop.
19
19 Some more examples: Factorials Binary Search template int binarySearch( const vector & a, const Comparable & x, int low, int high ) { if( low > high ) return NOT_FOUND; int mid = ( low + high ) / 2; if( a[ mid ] < x ) return binarySearch( a, x, mid + 1, high ); else if( x < a[ mid ] ) return binarySearch( a, x, low, mid - 1 ); else return mid; }
20
20 function factorial function factorial(n) { if (n <= 1) { return n; } else { return n * factorial(n-1); }
21
21 Numerical Applications Modular exponentiation: Compute X N (mod P) Greatest common divisor: Compute gcd(A, B)
22
22 Modular exponentiation: Three rules: 1. If A=B (mod N), then for any C, A+C =B+C (mod N) 2. If A=B (mod N), then for any D, AD = BD (mod N) 3. If A=B (mod N), then for any positive P, A P =B P (mod N)
23
23 Continue… If N is even, X N = (X*X) N/2 If N is odd, X N = X*(X*X) N/2 template HugeInt power( const HugeInt & x, const HugeInt & n, const HugeInt & p ) { if( n == 0 ) return 1; HugeInt tmp = power( ( x * x ) % p, n / 2, p ); if( n % 2 != 0 ) tmp = ( tmp * x ) % p; return tmp; }
24
24 Divide and Conquer Given an instance of the problem to be solved, split this into several, smaller, sub-instances (of the same problem) independently solve each of the sub-instances and then combine the sub- instance solutions so as to yield a solution for the original instance.
25
25 The Maximum Contiguous Subsequence Sum Problem Consider {4, -3, 5, -2, -1, 2, 6, -2} Case 1: It resides entirely in the first half. Case 2: It resides entirely in the second half. Case 3: It begins in the first half but ends in the second half.
26
26 Continued… template Comparable maxSubSum( const vector & a, int left, int right ) { Comparable maxLeftBorderSum = 0, maxRightBorderSum = 0; Comparable leftBorderSum = 0, rightBorderSum = 0; int center = ( left + right ) / 2; if( left == right ) // Base Case. return a[ left ] > 0 ? a[ left ] : 0; Comparable maxLeftSum = maxSubSum( a, left, center ); Comparable maxRightSum = maxSubSum( a, center + 1, right ); for( int i = center; i >= left; i-- ) { leftBorderSum += a[ i ]; if( leftBorderSum > maxLeftBorderSum ) maxLeftBorderSum = leftBorderSum; } for( int j = center + 1; j <= right; j++ ) { rightBorderSum += a[ j ]; if( rightBorderSum > maxRightBorderSum ) maxRightBorderSum = rightBorderSum; } return max3( maxLeftSum, maxRightSum, maxLeftBorderSum + maxRightBorderSum ); }
27
27 Analysis of Divide and Conquer Recurrence T(N) = 2T(N/2) + O(N) Result: T(N)/N = T(1)/1 +logN
28
28 Common Errors Forgetting a base case Overlapping recursive calls Using recursion in place of a simple loop.
29
29 In class exercises Question 8.1, 8.3, 8.4
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.