1 / 28

Recursion

Recursion. CMPE231, Spring 2012 Aleaxander G. Chefranov. Recursive Definition and Processes. π is defined as the ratio of the circumference of a circle to its diameter Factorial N! is defined as the product of integers between n and 1 N!=1 if n=0 N!=n(n-1)..2*1 if n>0 Prod=1;

flavio
Download Presentation

Recursion

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov

  2. Recursive Definition and Processes π is defined as the ratio of the circumference of a circle to its diameter Factorial N! is defined as the product of integers between n and 1 N!=1 if n=0 N!=n(n-1)..2*1 if n>0 Prod=1; For(x=n;x>0;x--) prod*=x; Return prod; Iterative algorithm

  3. Recursive Definition and Processes N!=1 if n=0 N!=n*(n-1)! If n>0 Recursive definition If(n==0) fact=1; Else{ x=n-1; find the value of X!. Call it y; fact=n*y; }/*end else*/

  4. Examples Multiplication of natural numbers A*b=a if b==1 A*b=a*(b-1)+a if b>1 Fibonacci Sequence Fib(n)=n if n==0 or n==1 Fib(n)=fib(n-2)+fib(n-1) if n>=2 If(n<=1) return n; Lofib=0; Hifib=1; For(i=2;i<=n;i++){ x=lofib; lofib=hifib; hifib=x+lofib; }/* end for*/ Return hifib;

  5. Examples Binary Search Recursive algorithm to search a sorted array a for an element x between a[low] and a[high]. The algorithm returns an index of a such that a[index] equals x if such an index exists between low and high. If x is not found in that portion of the array, binsrch returns -1 (in C, no element a[-1] can exist) If (low>high) return -1; Mid=(low+high)/2; If(x==a[mid]) return mid; If (x<a[mid]) search for x in a[low] to a[mid-1]; Else search for x in a[mid+1] to a[high];

  6. Properties of Recursive definitions of Algorithms It is not to generate an infinite sequence of calls to itself There must be a way out of the sequence of recursive calls Factorial: 0!=1 Multiplication: a*1=a Fibonacci seq.: fib(0)=0; fib(1)=1; Binary search: if(low>high)return -1; if(x==a[mid]) return mid; Any invocation of a recursive algorithm must eventually reduce to some manipulation of one or more simple, or nonrecursive cases.

  7. Recursion in C Int fact(int n){ int x,y; if(n==0) return 1; x=n-1; y=fact(x); return n*y; }/*end fact*/

  8. Recursion in C Stack is used to keep the successive generations of local variables and parameters Each time, a recursive function is entered, a new allocation of its variables is pushed on top of the stack. Any reference to a local variable is through the current top of the stack. When the function returns, the stack is popped, the top allocation is freed, and the previous allocation becomes the current stack top to be used for referencing local variables

  9. Recursion in C Int mult(int a, int b){ return(b==1?a:mult(a,b-1)+a); }/*end mult*/ Int fact(int n){ return(n==0?1:n*fact(n-1)); }/*end fact*/

  10. Recursion in C Int fib(int n){ int x,y; if(n<=1) return n; x=fib(n-1); y=fib(n-2); return (x+y); }/*end fib*/

  11. Recursion in C Intbinsrch(int a[], int x, int low, int high){ int mid; if (low>high) return -1; mid=(low+high)/2; return(x==a[mid]?mid:x<a[mid]? binsrch(a,x,low,mid-1): binsrch(a,x,mid+1,high); }/*end binsrch*/ Int a[ARRAYSIZE]; i=binsrch(a,x,0,n-1); Global variables may be used instead of parameters Int a[ARRAYSIZE], x; i=binsrch(0,n-1); Intbinsrch(int low, int high);

  12. Recursive Chains

  13. Recursive Definition of Algebraic Expressions • An expression is a term followed by a plus sign, or a term alone • A term is a factor followed by an asterisk followed by a factor, or a factor alone • A factor is either a letter or an expression enclosed in parenthesis Intgetsymb(char str[],intlength,int *ppos){ char c; if(*ppos<length) c=str[*ppos]; else c=‘ ‘; (*ppos)++; return c; }

  14. Expressions #include <stdio.h> #include <ctype.h> #define TRUE 1 #define FALSE 0 #define MAXSTRSIZE 100 Void readstr(char *, int); Intexpr(char *, int, int *); Int term(char *, int, int *); Intgetsymb(char *, int, int *); Int factor(char *, int, int *);

  15. Expressions (cont 1) Void main(){ char str[MAXSTRSIZE]; int length, pos; readstr(str, &length); pos=0; if(expr(str, length, &pos)==TRUE && pos>=length) printf(“Valid\n”); else printf (“Invalid\n”); }/*end main*/

  16. Expressions (cont 2) Intexpr(char str[], int length, int *ppos){ if(term(str, length, ppos)==FALSE) return FALSE; if(getsymb(str, length, ppos)!=‘+’){ (*ppos)--; return TRUE; } return term(str, length, ppos); }/*end expr*/

  17. Expressions (cont 3) Int term(char str[], int length, int *ppos){ if(factor(str, length, ppos)==FALSE) return FALSE; if(getsymb(str, length, ppos)!=‘*’){ (*ppos)--; return TRUE; } return factor(str, length, ppos); }/*end term*/

  18. Expressions (cont 4) Int factor(char str[], int length, int *ppos){ int c; if((c=getsymb(str,length,ppos))!=‘(‘) return isalpha(c); return expr(str, length, ppos) && getsymb(str, length, ppos)==‘)’); }/*end factor*/

  19. Towers of Hanoi Problem Three pegs, A, B, and C, exist. Five disks of differing diameters are placed on peg A so that a larger disk is always below a smaller disk. The object is to move the five disks to peg C, using peg B as auxiliary. Only the top disk on any peg may be moved to any other peg, and a larger disk may never rest on a smaller one.

  20. Towers of Hanoi Problem Let’s consider general case of n disks. Suppose that we had a solution for n-1 disks and could state solution for n disks in terms of the solution for n-1 disks. Then the problem would be solved. This is true because in the trivial case of one disk (continually subtracting 1 from n will eventually produce 1), the solution is simple: merely move the single disk from peg A to peg C.

  21. Towers of Hanoi Problem Move n disks from A to C using B as auxiliary • If n==1, move the single disk from A to C and stop • Move the top n-1 disks from A to B, using C as auxiliary • Move the remaining disk from A to C • Move the n-1 disks from B to C, using A as auxiliary

  22. Towers of Hanoi Problem How to represent actions? Design of inputs and outputs If necessary, a programmer can convert internal representation to the user’s form Output: Move disk nnn from peg yyy to peg zzz The action to be taken for a solution would be to perform each of the output statements in the order they appear in the output

  23. Towers of Hanoi Problem What shall be parameters of the function? Void main(){ int n; scanf(“%d”, &n); towers(paramters); }/*end main*/

  24. Towers of Hanoi Problem #include <stdio.h> Void towers(int n, char frompeg, char topeg, char auxpeg); Void main(){ int n; scanf(“%d”, &n); towers(n, ‘a’,’c’,’b’); }/*end main*/

  25. Towers of Hanoi Problem Void towers(int n, char frompeg, char topeg, char auxpeg){ if(n==1){ printf(“\nmove disk 1 from peg %c to peg %c”, frompeg, topeg); return; }/*end if*/ towers(n-1, frompeg, auxpeg, topeg); printf(“\nmove disk %d from peg %c to peg %c”, n,frompeg, topeg); towers(n-1,auxpeg, topeg, frompeg); }/*end towers*/

  26. Towers of Hanoi Problem Move disk 1 from peg a to peg b Move disk 2 from peg a to peg c Move disk 1 from peg b to peg c Move disk 3 from peg a to peg b Move disk 1 from peg c to peg a Move disk 2 from peg c to peg b Move disk 1 from peg a to peg b Move disk 4 from peg a to peg c Move disk 1 from peg b to peg c Move disk 2 from peg b to peg a Move disk 1 from peg c to peg a Move disk 3 from peg b to peg c Move disk 1 from peg a to peg b Move disk 2 from peg a to peg c Move disk 1 from peg b to peg c

  27. Efficiency of Recursion In general, a nonrecursive version of a program will execute more efficiently in terms of time and space than a recursive version. This is because overhead involved in entering and exiting a block is avoided in the nonrecursive version. However, sometimes a recursive solution is the most natural and logical way of solving a problem. A nonrecursive solution involving stacks is more difficult to develop and and mor prone to errors

  28. Efficiency of Recursion Thus there is a conflict between machine efficiency and programmer efficiency. If a program is to be run very frequently, so that increased efficiency in execution speed significantly increases throughput, the extra investment in programming is worthwhile. Even in such cases, it is better to have at first recursive version, and then modify it to a nonrecursive one.

More Related