570 likes | 591 Views
CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++. Prof. Amr Goneid AUC Part 12. Recursion. Recursion. Recursion. Definition Examples from Math Functions Why Recursion Rules for Recursion General Recursive Structures Famous Methods The Role of the Stack
E N D
CSCE 110PROGRAMMINGFUNDAMENTALSWITH C++ Prof. Amr Goneid AUC Part 12. Recursion Prof. amr Goneid, AUC
Recursion Prof. amr Goneid, AUC
Recursion • Definition • Examples from Math Functions • Why Recursion • Rules for Recursion • General Recursive Structures • Famous Methods • The Role of the Stack • Recursive Array processing using Exclude & Conquer • Recursive Array processing using Divide & Conquer • More Examples • Iterative VS Recursive Algorithms Prof. amr Goneid, AUC
1. Definition • recurFrom the Latin, re- = back +currere = to runTo happen again, especially at repeated intervals. • Many problems can be solved recursively, e.g. games of all types from simple ones like the Towers of Hanoi problem to complex ones like chess. • If a data structure may be defined recursively, it may be processed by a recursive function! Prof. amr Goneid, AUC
Recursive Functions • Has the the ability to call itself. • A finite number of recursive calls with different input parameters in each call. • Desired result is obtained from current action and the contributions of previous actions (history). • Terminal action is predefined (does not need previous history). • The termination condition (Base Case) is obviously extremely important. If it is omitted, then the function will continue to call itself indefinitely. Prof. amr Goneid, AUC
How It Works Big Problem (n) (General Case) n-1 n-2 Problem Gets Smaller Combine Base Case Get Previous History Prof. amr Goneid, AUC
2. Examples from Math Functions • Sum of the first n integers Sum(n) = 1+2+3+….+(n-1)+n // An Iterative Algorithm int sum (int n) { int i; int s = 0; for ( i = 1; i <= n; i++) s += i; return s; } Prof. amr Goneid, AUC
Recursive Sum Algorithm The sum of the first n integers is defined as: // A Recursive Algorithm int sum (int n){ if ( n == 1) return 1; else return sum(n-1) + n; } Prof. amr Goneid, AUC
Recursive Sum Algorithm(How it works) When we call sum(n), e.g. int k = sum(3); 6 sum (3) ……. 3 + sum(2) A general case 3 sum (2) ……. 2 + sum(1) Base case 1 sum(1) return 1 Prof. amr Goneid, AUC
3. Why Recursion • When current result depends on previous history. • Some problems are easier to code recursively. • When processing a large data structure that is composed of similar but smaller structures (e.g. trees). Prof. amr Goneid, AUC
4. Rules for Recursion • There must be a base case. • There is a general case other than the base case. • There is a path from a general case to the base case. • Successive recursive calls should take us towards the base case. The problem should get smaller in that direction. Prof. amr Goneid, AUC
5. General Recursive Structures • Structure(1): if (Base Case) {Terminal Action}; else {General Case Actions}; • Structure(2): if (! Base Case) {General case Actions}; Prof. amr Goneid, AUC
Examples from Math Functions • Factorial of n = n! = 1*2*3…*n = Hence Factorial(n) = 1 for n = 0 (base case) = n * Factorial(n-1) for n > 0 Prof. amr Goneid, AUC
Examples • An Iterative Factorial Function: int factorial (int n) { int i , f ; f = 1; if ( n > 0 ) for (i = 1; i <= n; i++) f * = i ; return f ; } Prof. amr Goneid, AUC
Examples • A Recursive Factorial Function: int factorial (int n) { if (n <= 0) return 1; else return ( n * factorial (n-1)); } e.g. m = factorial(4); Prof. amr Goneid, AUC
Factorial Tracing Prof. amr Goneid, AUC
Example: Power Function • A numeric value x raised to an integer power: Prof. amr Goneid, AUC
Power Function • A Recursive Function to return xn: double power (double x, int n) { if (n == 0 ) return 1.0; else return ( x * power(x,n-1)); } e.g. y = power(x , 5); Prof. amr Goneid, AUC
Examples • A Recursive function to print elements of an array A from index s through index e. Main call may be printlist(A,0,n-1): void printlist (int A[ ], int s, int e) { if (s <= e ) { cout << A[s]; printlist (A, s+1, e); } } Prof. amr Goneid, AUC
6. Famous Methods • Exclude and Conquer n 1 n-1 1 1 Base Prof. amr Goneid, AUC
Famous Methods • Divide and Conquer n n/2 n/2 n/4 n/4 Base Prof. amr Goneid, AUC
7. The Role of the Stack • Each call to a module pushes a stack frame on the stack. One stack frame has 3 items: • Where the jump to the module came from. • The input parameters • The result (or output parameters). Then it pops them out, returning results to the calling module. Pop Push Prof. amr Goneid, AUC
The Role of the Stack • Example: factorial(2) returns 2 factorial(1) * 2 = 2 factorial(0) * 1 = 1 1 Base Case Prof. amr Goneid, AUC
The Role of the Stack Prof. amr Goneid, AUC
8. Recursive Array processing using Exclude & Conquer • Recursive sum of array elements from location s through location e. int array_sum (int A[ ], int s, int e) { if (s == e) return A[s]; else return (A[s] + array_sum (A, s+1, e)); } Prof. amr Goneid, AUC
Recursive Array processing using Exclude & Conquer • Number of zero elements in an array from location s through location e. int nzeros (int A[ ], int s, int e) { int k = (A[s] == 0? 1 : 0); if (s == e) return k; else return (k + nzeros (A, s+1, e)); } Prof. amr Goneid, AUC
Recursive Array processing using Exclude & Conquer • Reversing an Array void ReverseArray (int A[ ], int s, int e) { if (s < e) { swap (A[s] , A[e]); ReverseArray ( A , s+1, e-1);} } Prof. amr Goneid, AUC
Recursive Sequential Search • Recursive Sequential Search of x in array A from location s through location e. int LinSearch (int A[ ], int x, int s, int e) { if (x == A[s]) return s; else if (s == e) return -1; else return LinSearch (A,x,s+1,e); } Prof. amr Goneid, AUC
Recursive Selection Sort • Recursive Selectsort of array A from location s through location e. Invoke e.g. as SelectSort(A , 1 , n) void SelectSort (int A[ ], int s, int e) { int m; if (s < e) { m = index_of_min(A,s,e); swap(A[m] , A[s]); SelectSort (A , s+1 , e); } } Prof. amr Goneid, AUC
9. Recursive Array Processing using Divide & Conquer • Maximum value in an array from location s through location e. • Assume we have a function that returns the greater of two values (a,b) int max2 (int a, int b) { return ((a > b)? a : b); } Prof. amr Goneid, AUC
Maximum in an Array int maximum (int a[ ], int s, int e) { // Base Case if (s == e) return a[s]; else // General Case { int m = (s + e)/2; // Divide in the middle int maxL = maximum (a , s , m); // Conquer left half int maxR = maximum (a , m+1 , e); // Conquer right return max2 ( maxL , maxR); // Combine } } Prof. amr Goneid, AUC
Recursive Binary Search • Search for an element x in an array A of elements sorted in ascending order. The function Bsearch (A,x,s,e) returns the index of x if found and -1 otherwise. A s mid e Prof. amr Goneid, AUC
Recursive Algorithm int Bsearch (int A[ ], int x, int s, int e) { int mid; // Base case: No elements left, search failed if (s > e) return -1; else { // General case mid = (s+e) / 2; // Divide in the middle if (x == A[mid]) return mid; // Success at mid else (if x > A[mid]) // Conquer right return Bsearch(A,x,mid+1,e); else // Conquer left return Bsearch(A,x,s,mid-1); } } Prof. amr Goneid, AUC
10. More ExamplesThe Towers of Hanoi In the Towers of Hanoi game, there are 3 pegs (A , B , C) and N disks with varying sizes that can be stacked on a peg. The objective is to move all the disks from peg (A) to peg (C), probably by using the auxiliary peg (B). At any moment, no larger peg can be placed on top of a smaller one. Prof. amr Goneid, AUC
The Towers of Hanoi For example: To move one disk from A to C: Move disk1 from A to C To move two disks (top is 1, bottom is 2): Move 1 from A to B Move 2 from A to C Move 1 from B to C To move N disks from A to C and we already know how to move N-1 disks from any one peg to another: Move the top N-1 disks by a series of legal moves from A to B using C Move Disk N from A to C directly Move N-1 disks from B to C using A Prof. amr Goneid, AUC
Algorithm Obviously, this is a recursive problem that can be solved by the following recursive algorithm: Towers (N, A , C , B) { if N = 1 move disk 1 from A to C directly else { Towers ( N-1 , A , B , C) Move disk N from A to C directly Towers ( N-1 , B , C , A) } } Prof. amr Goneid, AUC
Animation An animation is available at: http://www.cosc.canterbury.ac.nz/people/mukundan/dsal/ToHdb.html Prof. amr Goneid, AUC
Euclide’s Algorithm for the GCD (Recursive Version) //Computes gcd(m, n) by Euclid’s algorithm //Input: Two nonnegative, not-both-zero integers m and n //Output: Greatest common divisor of m and n function gcd(m, n) if n = 0 return m else return gcd (n, m mod n) "The Euclidean algorithm is the granddaddy of all algorithms, because it is the oldest nontrivial algorithm that has survived to the present day”. Donald Knuth, The Art of Computer Programming, Vol. 2 Prof. Amr Goneid, AUC
Non-Recursive Algorithm ALGORITHM Euclid (m, n) //Computes gcd(m, n) by Euclid’s algorithm //Input: Two nonnegative, not-both-zero integers m and n //Output: Greatest common divisor of m and n while n != 0 do r ←m mod n m←n n←r return m Prof. Amr Goneid, AUC
Recursive Power Function(Divide & Conquer) A power function can be defined as follows: Prof. Amr Goneid, AUC
Recursive Power Function The recursive function would be: double pow (double x, int n) { if (n == 0) return 1.0; else if (n == 1) return x; else if (n%2) return pow (x*x, n/2) * x; else return pow (x*x, n/2); Prof. Amr Goneid, AUC
Binary Tree Traversal • A Binary Tree is a special data structure where a node has a maximum of two children • The nodes in the BST can be implemented as a linked structure: t 32 16 45 40 Prof. Amr Goneid, AUC
Binary Tree Traversal • Algorithm: Pre-order Traversal (Visit parent before children) void PreOrder ( tree T) { if ( T != NULL) { Visit (T); PreOrder (T->left); PreOrder (T->right); } } • The resulting visit order = {a} {b , d , e} {c , f } T 1 a 5 2 b c 4 3 f d e 6 Prof. Amr Goneid, AUC
Fractal Star Example: a Fractal Algorithm The following function draws recursive squares (called a fractal star). The drawing primitive is Box (x , y , n) which draws a square of side (n) pixels centered at (x,y) : void STAR( int x, int y, int n) { if (n > 1) { STAR(x-n , y+n , n/2); STAR(x+n , y+n , n/2); STAR(x-n , y-n , n/2); STAR(x+n , y-n , n/2); Box(x , y , n); } } Prof. Amr Goneid, AUC
11. Iterative VS Recursive Algorithms • Recursive Algorithms can be more elegant in programming and easier to understand. • They will cost about 5% more time than an equivalent iterative algorithm. • BUT, Sometimes a recursive algorithm can be a Disaster Prof. Amr Goneid, AUC
Example: Fibonacci Numbers • Fibonacci numbers represent the sequence: 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,... • Introduced by Leonardo Fibonacci (1202) • Can be computed by the recurrence relation: Prof. Amr Goneid, AUC
Fibonacci Numbers Fibonacci numbers are closely related to the Golden Ratio φ since: Prof. Amr Goneid, AUC
The Golden Ratio Prof. Amr Goneid, AUC
In Nature Prof. Amr Goneid, AUC
In Nature Prof. Amr Goneid, AUC