with c
play

WITH C++ Prof. Amr Goneid AUC Part 12. Recursion Prof. amr - PowerPoint PPT Presentation

CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 12. Recursion Prof. amr Goneid, AUC 1 Recursion Prof. amr Goneid, AUC 2 Recursion Definition Examples from Math Functions Why Recursion Rules for


  1. CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 12. Recursion Prof. amr Goneid, AUC 1

  2. Recursion Prof. amr Goneid, AUC 2

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

  4. 1. Definition  recur From the Latin, re- = back + currere = to run To 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 4

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

  6. How It Works Big Problem (n) (General Case) n-1 n-2 Problem Combine Gets Smaller Base Case Get Previous History Prof. amr Goneid, AUC 6

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

  8. Recursive Sum Algorithm The sum of the first n integers is defined as: =   1 n 1   n ∑ =  −  i n 1 ∑ + > ( i ) n n 1   = i 1   = i 1 // A Recursive Algorithm int sum (int n){ if ( n == 1) return 1; else return sum(n-1) + n; } Prof. amr Goneid, AUC 8

  9. Recursive Sum Algorithm (How it works) When we call sum(n), e.g. int k = sum(3); 6 sum (3) A general case ……. 3 + sum(2) sum (2) 3 ……. 2 + sum(1) Base case 1 sum(1) return 1 Prof. amr Goneid, AUC 9

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

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

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

  13. Examples from Math Functions n ∏  Factorial of n = n! = 1*2*3…*n = i = i 1 =   1 n 0 =   n ! − >   n n n ( 1)! 0 Hence Factorial(n) = 1 for n = 0 (base case) = n * Factorial(n-1) for n > 0 Prof. amr Goneid, AUC 13

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

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

  16. Factorial Tracing Prof. amr Goneid, AUC 16

  17. Example: Power Function  A numeric value x raised to an integer power: =   1 n 0 =  n  x − > n 1   x x n 0 Prof. amr Goneid, AUC 17

  18. Power Function  A Recursive Function to return x n : 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 18

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

  20. 6. Famous Methods  Exclude and Conquer n 1 n-1 1 1 Base Prof. amr Goneid, AUC 20

  21. Famous Methods  Divide and Conquer n n/2 n/2 n/4 n/4 Base Prof. amr Goneid, AUC 21

  22. 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. 3 Results Pop 2 Input params Push 1 Where from Prof. amr Goneid, AUC 22

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

  24. The Role of the Stack 1 n = 0 Addr3 1 ? ? n = 1 n = 1 n = 1 Addr2 Addr2 Addr2 2 ? ? ? ? n = 2 n = 2 n = 2 n = 2 n = 2 Addr1 Addr1 Addr1 Addr1 Addr1 Prof. amr Goneid, AUC 24

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

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

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

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

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

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

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

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

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

  34. 10. More Examples The 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 34

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

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

  37. Animation An animation is available at: http://www.cosc.canterbury.ac.nz/people/m ukundan/dsal/ToHdb.html Prof. amr Goneid, AUC 37

Recommend


More recommend