recursion cmpe231, spring 2012 aleaxander g. chefranov 1

28
Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Upload: gertrude-jordan

Post on 01-Jan-2016

224 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Recursion

CMPE231, Spring 2012 Aleaxander G. Chefranov

1

Page 2: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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 1N!=1 if n=0N!=n(n-1)..2*1 if n>0Prod=1;For(x=n;x>0;x--) prod*=x;Return prod;Iterative algorithm

2

Page 3: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Recursive Definition and Processes

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

3

Page 4: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

ExamplesMultiplication of natural numbersA*b=a if b==1A*b=a*(b-1)+a if b>1Fibonacci SequenceFib(n)=n if n==0 or n==1Fib(n)=fib(n-2)+fib(n-1) if n>=2If(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;

4

Page 5: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

ExamplesBinary SearchRecursive 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];

5

Page 6: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Properties of Recursive definitions of Algorithms

It is not to generate an infinite sequence of calls to itselfThere must be a way out of the sequence of recursive

callsFactorial: 0!=1Multiplication: a*1=aFibonacci 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.

6

Page 7: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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*/

7

Page 8: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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

8

Page 9: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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*/

9

Page 10: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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*/

10

Page 11: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Recursion in CInt binsrch(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 parametersInt a[ARRAYSIZE], x;i=binsrch(0,n-1);Int binsrch(int low, int high);

11

Page 12: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Recursive ChainsA(formal parameters){.. b(arguments);..}/*end of a*/

b(formal parameters){.. a(arguments);..}/*end of b*/

12

Page 13: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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 parenthesisInt getsymb(char str[],int length,int *ppos){ char c; if(*ppos<length) c=str[*ppos]; else c=‘ ‘; (*ppos)++; return c;}

13

Page 14: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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

14

Page 15: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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*/

15

Page 16: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Expressions (cont 2)

Int expr(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*/

16

Page 17: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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*/

17

Page 18: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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*/

18

Page 19: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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.

19

Page 20: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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.

20

Page 21: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Towers of Hanoi Problem

Move n disks from A to C using B as auxiliary1.If n==1, move the single disk from A to C and

stop2.Move the top n-1 disks from A to B, using C as

auxiliary3.Move the remaining disk from A to C4.Move the n-1 disks from B to C, using A as

auxiliary

21

Page 22: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Towers of Hanoi Problem

How to represent actions?Design of inputs and outputsIf necessary, a programmer can convert internal

representation to the user’s formOutput:Move disk nnn from peg yyy to peg zzzThe action to be taken for a solution would be to

perform each of the output statements in the order they appear in the output

22

Page 23: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Towers of Hanoi Problem

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

23

Page 24: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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*/

24

Page 25: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Towers of Hanoi ProblemVoid 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*/

25

Page 26: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

Towers of Hanoi ProblemMove disk 1 from peg a to peg bMove disk 2 from peg a to peg cMove disk 1 from peg b to peg cMove disk 3 from peg a to peg bMove disk 1 from peg c to peg aMove disk 2 from peg c to peg bMove disk 1 from peg a to peg bMove disk 4 from peg a to peg cMove disk 1 from peg b to peg cMove disk 2 from peg b to peg aMove disk 1 from peg c to peg aMove disk 3 from peg b to peg cMove disk 1 from peg a to peg bMove disk 2 from peg a to peg cMove disk 1 from peg b to peg c

26

Page 27: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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

27

Page 28: Recursion CMPE231, Spring 2012 Aleaxander G. Chefranov 1

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.

28