ds lec 8 recursion

32
Recursion Recursion Data Structures Data Structures Lecture # 9 Lecture # 9

Upload: williamsock

Post on 16-Feb-2016

229 views

Category:

Documents


0 download

DESCRIPTION

Data Structures, Tree, Queue

TRANSCRIPT

Page 1: DS Lec 8 Recursion

RecursionRecursionData StructuresData Structures

Lecture # 9Lecture # 9

Page 2: DS Lec 8 Recursion

Towards RecursionTowards RecursionFactorial Function:Factorial Function:

Given a +ive integer n, n factorial is defined as the product Given a +ive integer n, n factorial is defined as the product of all integers between 1 and n, including n.of all integers between 1 and n, including n.n != 1 n != 1 if n == 0if n == 0

n != n*(n-1) * (n-2) * - - - - -* 1 n != n*(n-1) * (n-2) * - - - - -* 1 if n > 0if n > 0Algorithm that accepts an integer n and returns the value of Algorithm that accepts an integer n and returns the value of n!n!prod = 1;prod = 1;for(x = n; x > 0; x--)for(x = n; x > 0; x--)prod*= x;prod*= x;return(prod); return(prod); This algorithm is an This algorithm is an iterativeiterative algorithm. algorithm.

Page 3: DS Lec 8 Recursion

Towards RecursionTowards RecursionMultiplying n by the product of all integers from Multiplying n by the product of all integers from n-1 to 1 yields the product of all integers from n n-1 to 1 yields the product of all integers from n to 1.to 1.For any n > 0, we see that n! equals n * (n-1)!For any n > 0, we see that n! equals n * (n-1)!n! = 1 n! = 1 if n == 0if n == 0

n! = n(n-1)! n! = n(n-1)! if n > 0if n > 0Is this a recursive definition?Is this a recursive definition?A definition which defines an object in terms of A definition which defines an object in terms of a simpler case of itself, is called a a simpler case of itself, is called a recursive recursive definitiondefinition

Page 4: DS Lec 8 Recursion

Problem To SolvedProblem To Solved1.1. 5! = 5 * 4! 5! = 5 * 4!2.2. - - - - - - - 4! = 4 * 3!- - - - - - - 4! = 4 * 3!3.3. - - - - - - - - - - - - - - 3! = 3 * 2!- - - - - - - - - - - - - - 3! = 3 * 2!4.4. - - - - - - - - - - - - - - - - - - - - - 2! = 2 * 1!- - - - - - - - - - - - - - - - - - - - - 2! = 2 * 1!5.5. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1! = 1 * 0!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1! = 1 * 0!6.6. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -0! = 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -0! = 1 Solve from line 6 to 1. Solve from line 6 to 1. 6´- - - - - - - - - 0! = 16´- - - - - - - - - 0! = 15´- - - - - - - - - 1! = 1*0! = 1 * 1 = 15´- - - - - - - - - 1! = 1*0! = 1 * 1 = 14´- - - - - - - - - 2! = 2*1! = 2 * 1 = 24´- - - - - - - - - 2! = 2*1! = 2 * 1 = 23´- - - - - - - - - 3! = 3*2! = 3 * 2 = 63´- - - - - - - - - 3! = 3*2! = 3 * 2 = 62´- - - - - - - - - 4! = 4*3! = 4 * 6 = 242´- - - - - - - - - 4! = 4*3! = 4 * 6 = 241´- - - - - - - - - 5! = 5*4! = 5 *24 = 1201´- - - - - - - - - 5! = 5*4! = 5 *24 = 120

Page 5: DS Lec 8 Recursion

Problem To SolvedProblem To Solved Multiplication of Natural NumberMultiplication of Natural Number The product a * b, where a and b are The product a * b, where a and b are

positive integers, may be defined as positive integers, may be defined as a * b = a a * b = a if b ==1if b ==1a * b = a * (b-1) + a a * b = a * (b-1) + a if b > 1if b > 1

e.g.e.g.6 * 3 = 6 * 2 + 66 * 3 = 6 * 2 + 6 = 6 * 1 + 6 + 6= 6 * 1 + 6 + 6 = 6 + 6 + 6= 6 + 6 + 6 = 18= 18

Page 6: DS Lec 8 Recursion

Problem To SolvedProblem To Solved Fibonnacci SequenceFibonnacci Sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . . . . . . 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . . . . . . . Each element is the sum of the two Each element is the sum of the two

preceding elements withpreceding elements withfib(0) = 0fib(0) = 0fib(1) = 1fib(1) = 1fib(n) = n fib(n) = n if n ==0 or n ==1if n ==0 or n ==1fib(n) = fib(n-2) + fib(n-1)fib(n) = fib(n-2) + fib(n-1) if n >= 2if n >= 2

e.g.e.g.

Page 7: DS Lec 8 Recursion

Problem To SolvedProblem To Solved

Fib(5)

Fib(3)

Fib(1) Fib(2)

Fib(0) Fib(1) Fib(0) Fib(1)Fib(1) Fib(2)

Fib(0) Fib(1)

Fib(3)

Fib(4)

Fib(2)

Page 8: DS Lec 8 Recursion

Problem To SolvedProblem To Solved All these problems have a All these problems have a

recursive definition.recursive definition. A definition which defines an A definition which defines an

object in terms of a simpler object in terms of a simpler case of itself, is called a case of itself, is called a recursive definition.recursive definition.

Page 9: DS Lec 8 Recursion

RecursionRecursion

Every recursive definition has two parts,Every recursive definition has two parts,

A Recursive part &A Recursive part &

A Non-Recursive part, also called as A Non-Recursive part, also called as Base Base CaseCase

e.g. in the recursive definition of n!e.g. in the recursive definition of n!n! = 1 n! = 1 if n == 0 if n == 0 Base CaseBase Casen! = n*(n-1) * (n-2) * - - - - -* 1 if n > 0 n! = n*(n-1) * (n-2) * - - - - -* 1 if n > 0 Recursive PartRecursive Part

Page 10: DS Lec 8 Recursion

RecursionRecursion The recursive part of the n! definition is used several The recursive part of the n! definition is used several

times, terminating with the non-recursive parttimes, terminating with the non-recursive part1.1. 5! = 5 * 4! 5! = 5 * 4!2.2. - - - - - - - 4! = 4 * 3!- - - - - - - 4! = 4 * 3!3.3. - - - - - - - - - - - - - - 3! = 3 * 2!- - - - - - - - - - - - - - 3! = 3 * 2!4.4. - - - - - - - - - - - - - - - - - - - - - 2! = 2 * 1!- - - - - - - - - - - - - - - - - - - - - 2! = 2 * 1!5.5. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1! = 1 * 0!- - - - - - - - - - - - - - - - - - - - - - - - - - - - - 1! = 1 * 0!6.6. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -0! = 1 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -0! = 1 Solve from line 6 to 1. Solve from line 6 to 1. 6´- - - - - - - - - 0! = 16´- - - - - - - - - 0! = 15´- - - - - - - - - 1! = 1*0! = 1 * 1 = 15´- - - - - - - - - 1! = 1*0! = 1 * 1 = 14´- - - - - - - - - 2! = 2*1! = 2 * 1 = 24´- - - - - - - - - 2! = 2*1! = 2 * 1 = 23´- - - - - - - - - 3! = 3*2! = 3 * 2 = 63´- - - - - - - - - 3! = 3*2! = 3 * 2 = 62´- - - - - - - - - 4! = 4*3! = 4 * 6 = 242´- - - - - - - - - 4! = 4*3! = 4 * 6 = 241´- - - - - - - - - 5! = 5*4! = 5 *24 = 1201´- - - - - - - - - 5! = 5*4! = 5 *24 = 120

Page 11: DS Lec 8 Recursion

RecursionRecursion All recursive definitions have to All recursive definitions have to

have a have a base case.base case. If they didn't, there would be no If they didn't, there would be no

way to terminate the recursive path.way to terminate the recursive path. Such a definition would cause Such a definition would cause

infinite recursion.infinite recursion. This problem is similar to an infinite This problem is similar to an infinite

loop. loop.

Page 12: DS Lec 8 Recursion

RecursionRecursion How can we translate How can we translate

recursive definition into a recursive definition into a computer program?computer program?

Recursion is a fundamental Recursion is a fundamental programming technique that can programming technique that can provide a solution to the problems,provide a solution to the problems,

which have a recursive definition.which have a recursive definition.

Page 13: DS Lec 8 Recursion

Recursive ProgrammingRecursive Programming A A methodmethod which can invoke which can invoke

itselfitself, if set up that way, is , if set up that way, is called a recursive method.called a recursive method.

The code of a recursive method The code of a recursive method must be structured to handle must be structured to handle both the base case and the both the base case and the recursive case.recursive case.

Page 14: DS Lec 8 Recursion

Recursive ProgrammingRecursive Programming Each call to the method sets up a Each call to the method sets up a

new execution environment, with new execution environment, with new parameters and local new parameters and local variables.variables.

As always, when the method As always, when the method completes, control returns to the completes, control returns to the method that invoked it (which may method that invoked it (which may be an earlier invocation of itself).be an earlier invocation of itself).

Page 15: DS Lec 8 Recursion

Recursive ProgrammingRecursive Programming Consider again the recursive definition of the factorial of a Consider again the recursive definition of the factorial of a

positive integer.positive integer.n! = 1 n! = 1 if n == 0if n == 0 Base CaseBase Casen! = n*(n-1) * (n-2) * - - - - -* 1 if n > 0n! = n*(n-1) * (n-2) * - - - - -* 1 if n > 0 Recursive PartRecursive Part We can write the recursive function using this definition asWe can write the recursive function using this definition asint factorial(n)int factorial(n)

{{if(n == 0)if(n == 0) //Base Case//Base Casereturn 1;return 1;elseelsereturn n * factorial(n-1); return n * factorial(n-1); //Recursion//Recursion}}

Page 16: DS Lec 8 Recursion

Recursive ProgrammingRecursive Programmingmain

factorial(3)

factorial(2)

factorial(1)

factorial(3)

2*factorial(1)

3 * factorial(2)

return 1

return 6

1*factorial(0)

factorial(0)return 1

return 2

Page 17: DS Lec 8 Recursion

Recursive ProgrammingRecursive Programming Multiplication of natural numbers:Multiplication of natural numbers: The product a * b, where a and b are positive integers, The product a * b, where a and b are positive integers,

may be defined as may be defined as a * b = a a * b = a if b ==1if b ==1a * b = a * (b-1) + a a * b = a * (b-1) + a if b > 1if b > 1

int multiplication(int a, int b)int multiplication(int a, int b){{

if(b == 1)if(b == 1)return a;return a;else if(b > 1)else if(b > 1)return multiplication(a, b-1) + a;return multiplication(a, b-1) + a;

}}

Page 18: DS Lec 8 Recursion

Recursive ProgrammingRecursive Programming Fibonnacci SequenceFibonnacci Sequence

fib(n) = n fib(n) = n if n ==0 or n ==1if n ==0 or n ==1fib(n) = fib(n-2) + fib(n-1)fib(n) = fib(n-2) + fib(n-1) if n >= 2if n >= 2int fib(int n)int fib(int n){{if(n == 0 || n == 1)if(n == 0 || n == 1)return n;return n;else else return fib(n-2) + fib(n-1);return fib(n-2) + fib(n-1);}}

Page 19: DS Lec 8 Recursion

Hanoi TowerHanoi Tower PROBLEMPROBLEM

Given N discs (of decreasing size) stacked on Given N discs (of decreasing size) stacked on one needle and two empty needles, it is required one needle and two empty needles, it is required to stack all the discs onto a second needle in to stack all the discs onto a second needle in decreasing order of size. The third needle may decreasing order of size. The third needle may be used as temporary storage. The movement of be used as temporary storage. The movement of the discs is restricted by the following rules:the discs is restricted by the following rules:

1.  Only one disc may be moved at a time.1.  Only one disc may be moved at a time.2.  A disc may be moved from any needle to any 2.  A disc may be moved from any needle to any

other.other.3.  At no time may a larger disc rest upon a 3.  At no time may a larger disc rest upon a

smaller disc.smaller disc.

Page 20: DS Lec 8 Recursion

Hanoi TowerHanoi Tower

Needle ANeedle A Needle B Needle B Needle C Needle C (start of (start of (interme- (interme- (completion(completion problem)problem) diate) diate) of problem) of problem)

SOLUTION:SOLUTION:1.Move 1.Move N –1N –1 discs from discs from AA to to BB..2.Move disc 2.Move disc NN from from AA to to CC..3.Move 3.Move N –1N –1 discs from discs from BB to to CC..

Page 21: DS Lec 8 Recursion

Hanoi TowerHanoi Towervoid tower(char source, char destination, char void tower(char source, char destination, char

intermediate, int n)intermediate, int n){{

if(n==1) {if(n==1) {cout<<"Move disk 1 from needle "<<source<<" to cout<<"Move disk 1 from needle "<<source<<" to needle needle "<<destination<<endl;"<<destination<<endl; } } else {else {tower(source, intermediate, destination, n-1);tower(source, intermediate, destination, n-1);cout<<"Move disk "<<n<<" from needle cout<<"Move disk "<<n<<" from needle "<<source<<" to "<<source<<" to needle "<<destination<<endl;needle "<<destination<<endl;tower(intermediate, destination, source, n-1);tower(intermediate, destination, source, n-1);}}

}}

Page 22: DS Lec 8 Recursion

Hanoi TowerHanoi Towertower(‘A’, ‘C’, ‘B’, 3); //A is source, C is destinationtower(‘A’, ‘C’, ‘B’, 3); //A is source, C is destination

//B is intermediate//B is intermediate

Move disk 1 from A to CMove disk 1 from A to CMove disk 2 from A to BMove disk 2 from A to BMove disk 1 from C to BMove disk 1 from C to B

Move disk 3 from A to CMove disk 3 from A to CMove disk 1 from B to AMove disk 1 from B to AMove disk 2 from B to CMove disk 2 from B to CMove disk 1 from A to CMove disk 1 from A to C

Page 23: DS Lec 8 Recursion

Rules of RecursionRules of Recursion1.1. Base CaseBase Case There must be a way out for a recursive algorithm. It must not There must be a way out for a recursive algorithm. It must not

generate an infinite sequence of calls on itself.generate an infinite sequence of calls on itself. Without a non-recursive exit, no recursive function can ever be Without a non-recursive exit, no recursive function can ever be

computed.computed.

2.2. Making ProgressMaking ProgressFor the cases that are to be solved recursively, the For the cases that are to be solved recursively, the recursive call must always be to a case that makes recursive call must always be to a case that makes progress toward a base case.progress toward a base case.

Page 24: DS Lec 8 Recursion

Rules of RecursionRules of RecursionExampleExample1- - - - - - int Bad(int N)1- - - - - - int Bad(int N)2- - - - - - {2- - - - - - {3- - - - - - - - -if(N == 0)3- - - - - - - - -if(N == 0)4- - - - - - -- - - - - return 0;4- - - - - - -- - - - - return 0;5- - - - - - -- --else5- - - - - - -- --else6- - - - - - - - - - - - return Bad (N / 3+1) + N - 6- - - - - - - - - - - - return Bad (N / 3+1) + N -

1;1;7- - - - - - }7- - - - - - }

Page 25: DS Lec 8 Recursion

Rules of RecursionRules of Recursion3. Design Rule3. Design Rule

Assume that all the recursive calls work.Assume that all the recursive calls work.4. Compound Interest Rule4. Compound Interest Rule

Careful about duplication of the Work Careful about duplication of the Work Never duplicate work by solving the same instance of a problem in Never duplicate work by solving the same instance of a problem in

separate recursive calls.separate recursive calls. Example: Fibonacci NumbersExample: Fibonacci Numbers

ExampleExampleA +ive integer to be printed A +ive integer to be printed Assume that only I/O routines available will take a single digit Assume that only I/O routines available will take a single digit number and output it to the terminal.number and output it to the terminal.

Page 26: DS Lec 8 Recursion

Rules of RecursionRules of Recursion• Write a recursive algorithm to print the number digit by digitWrite a recursive algorithm to print the number digit by digit

void print_out(int N)void print_out(int N){{if(N < 10)if(N < 10) cout<<N;cout<<N;elseelse{{ print_out(N/10);print_out(N/10); cout<<(N%10);cout<<(N%10); }}} }

Page 27: DS Lec 8 Recursion

ExerciseExercise

1.1. The problem of computing the The problem of computing the sum of all the numbers between sum of all the numbers between 1 and any positive integer N can 1 and any positive integer N can be recursively defined as:be recursively defined as:

i = 1

N

i = 1

N-1

i = 1

N-2

= N + = N + (N-1) +

= etc.

Page 28: DS Lec 8 Recursion

ExerciseExerciseint sum(int n)int sum(int n){{if(n==1)if(n==1)

return n;return n;elseelse

return n + sum(n-1);return n + sum(n-1);}}

Page 29: DS Lec 8 Recursion

ExerciseExercise

2.2. Ackerman's function is defined Ackerman's function is defined recursively on a non negative recursively on a non negative integers as followsintegers as followsA(m, n) = n + 1A(m, n) = n + 1 if m = = 0if m = = 0A(m, n) = A(m-1, 1)A(m, n) = A(m-1, 1) if m != 0, n = = 0if m != 0, n = = 0A(m, n) = A(m-1, A(m, n-1))A(m, n) = A(m-1, A(m, n-1)) if m != if m != 0, n != 00, n != 0

Page 30: DS Lec 8 Recursion

ExerciseExerciseint ackerman(int m, int n)int ackerman(int m, int n){{if(m==0)if(m==0)

return n+1;return n+1;if(m!=0&&n==0)if(m!=0&&n==0)

return ackerman(m-1, 1);return ackerman(m-1, 1);if(m!=0&&n!=0)if(m!=0&&n!=0)

return ackerman(m-1, ackerman(m,n-1));return ackerman(m-1, ackerman(m,n-1));}}

Page 31: DS Lec 8 Recursion

ExerciseExercise

3.3. The Greatest Common Divisor (GCD) of The Greatest Common Divisor (GCD) of two positive integers x and y is defined as two positive integers x and y is defined as

GCD(x, y) = yGCD(x, y) = y if (y <= x && x % y if (y <= x && x % y

==0)==0)GCD(x, y) = GCD(y, x)GCD(x, y) = GCD(y, x) if (x < y)if (x < y)GCD(x, y) = GCD(y, x % y)GCD(x, y) = GCD(y, x % y) otherwiseotherwise

Page 32: DS Lec 8 Recursion

ExerciseExerciseint GCD(int x,int y)int GCD(int x,int y){{if (y <= x && x % y ==0)if (y <= x && x % y ==0)

return y;return y;else if (x < y)else if (x < y)

return GCD(y,x);return GCD(y,x);elseelse

return GCD(y, x % y);return GCD(y, x % y);}}