29
Recursion Recursion

Recursion

Embed Size (px)

DESCRIPTION

Recursion. Circular Definition (not useful). E.g., Projenitor : one who produces an offspring Offspring: one who is produced by a projenitor E.g., Oak: a tree that produces acorn Acorn: a nut produced by oak tree. Recursive Definition. Recursive Definition - PowerPoint PPT Presentation

Citation preview

RecursionRecursion

Circular Definition (not useful)Circular Definition (not useful)

E.g.,E.g., Projenitor: one who produces an offspringProjenitor: one who produces an offspring Offspring: one who is produced by a projenitorOffspring: one who is produced by a projenitor

E.g.,E.g., Oak: a tree that produces acornOak: a tree that produces acorn Acorn: a nut produced by oak treeAcorn: a nut produced by oak tree

Recursive DefinitionRecursive Definition

Recursive DefinitionRecursive Definition Uses the term being defined as part of the Uses the term being defined as part of the

definitiondefinition Is not a circular definitionIs not a circular definition Must have base case(s)Must have base case(s)

Factorial of n: n!Factorial of n: n!

n! = 1, when n = 0 // base casen! = 1, when n = 0 // base casen! = n (n – 1)!, when n > 0 // recursive casen! = n (n – 1)!, when n > 0 // recursive case

Recursive FunctionRecursive Function Recursive functionRecursive function

Invokes itself within the functionInvokes itself within the function Is an example of divide-and-conquor techniqueIs an example of divide-and-conquor technique

Recursive Recursive factorialfactorial function function

int fact(int n){int fact(int n){ if (n == 0) // base case if (n == 0) // base case return 1; return 1; else // recursive case else // recursive case return n * fact(n – 1); return n * fact(n – 1);}}

Invocation

cout << fact(4);

Recursive Recursive Factorial Factorial FunctionFunction

fact(4) return 4 * fact(3)

fact(3) return 3 * fact(2)

fact(2) return 2 * fact(1)

fact(1) return 1 * fact(0)

fact(0) return 1

fact(1) return 1 * 1

fact(2) return 2 * 1

fact(3) return 3 * 2

fact(4) return 4 * 3

Recursive FunctionsRecursive Functions

Consider a function for solving the count-Consider a function for solving the count-down problem from some number down problem from some number numnum down to down to 00:: Base case: when Base case: when numnum == == 00: :

the problem is solved and we “blast off!” the problem is solved and we “blast off!” Otherwise, Otherwise, numnum > > 00: we count off : we count off numnum and and

then recursively count down from then recursively count down from num-1num-1

14-14-66

Recursive FunctionsRecursive Functions

A recursive function for counting down to 0:A recursive function for counting down to 0:

void countDown(int num)void countDown(int num){{ if (num == 0) // base caseif (num == 0) // base case

cout << "Blastoff!"; cout << "Blastoff!"; else // recursiveelse // recursive {{ // call// call cout << num << ". . .";cout << num << ". . ."; countDown(num-1); countDown(num-1); }}}}

14-14-77

What Happens When Called?What Happens When Called?

14-14-88

third call tocountDown num is 0

countDown(1);

countDown(0);

// no // recursive// call

second call tocountDown num is 1

first call tocountDownnum is 2 OUTPUT:

2...

1...

Blastoff!

Fibonnaci NumberFibonnaci Number

fib(n) = 1, when n = 0fib(n) = 1, when n = 0fib(n) = 1, when n = 1fib(n) = 1, when n = 1fib(n) = fib(n -1) + fib(n – 2), when n > 1fib(n) = fib(n -1) + fib(n – 2), when n > 1

Fibonacci FunctionFibonacci Function

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

Your TurnYour Turn

Write a recursive function Write a recursive function sumOf(int n), sumOf(int n), which returns the sum of consecutive integers which returns the sum of consecutive integers between 1 and n.between 1 and n.

E.g., cout << sumOf(10) prints 55.E.g., cout << sumOf(10) prints 55.

SolutionSolution

int sumOf(int n){ if (n == 1) { return 1; } else { return n + sumOf(n - 1); }}

Your TurnYour Turn

Write a recursive function Write a recursive function power(double b, int x), power(double b, int x), which returns b^xwhich returns b^x(b raised to the power of x).(b raised to the power of x).

E.g., cout << power(2, 8) prints 256E.g., cout << power(2, 8) prints 256

SolutionSolutionint power(double b, int x){ double result; if (x == 0){ result = 1; } else if (x == 1){ result = b; } else { result = b * power(b, x – 1); } return result; }

Your TurnYour Turn

Write a recursive function Write a recursive function which reads a series of characters from the which reads a series of characters from the console and prints them backwordsconsole and prints them backwords. (A . (A sentinel value of ‘z’ signals the end of input.) sentinel value of ‘z’ signals the end of input.)

E.g., main() can contain the following:E.g., main() can contain the following:

int main() {int main() { cout << “Enter a series of chars.\n”; cout << “Enter a series of chars.\n”; printBackwards(); printBackwards(); … …}}

SolutionSolutionvoid printBackward() { char ch; cin >> ch; if (ch != 'z') { printBackward(); cout << ch; }}

Your TurnYour Turn Write a recursive function named Write a recursive function named

minimum(int a[], int count) minimum(int a[], int count) which returns the which returns the minimum value of an int array.minimum value of an int array.

E.g., main() can contain the following:E.g., main() can contain the following:

int main() {int main() { int a[]; int a[]; int count; int count; intializeArray(a, count); intializeArray(a, count); cout << “Min: “ << minimum(a, count); cout << “Min: “ << minimum(a, count); … …}}

SolutionSolutionint minimum(int a[], int count) { int min = a[count - 1]; if (count == 1) { return min; } else { if (min < minimum(a, count - 1)) return min; else return minimum(a, count - 1); }}

Your TurnYour Turn

Write a recursive function named Write a recursive function named greatestCommonFactor(int a, int b)greatestCommonFactor(int a, int b)which returns the greatest common facterwhich returns the greatest common facterbetween positive integers between positive integers aa and and bb..

GCF can be found from the following rules:GCF can be found from the following rules:

if b = 0, then GCF is a; otherwise, it is if b = 0, then GCF is a; otherwise, it is the GCF of b and (a mod b).the GCF of b and (a mod b).

SolutionSolutionint greatestCommonFactor(int a, int b){ if (b == 0) return a; else return lowestCommonFactor(b, a % b);}

Recursive Binary Search Recursive Binary Search FunctionFunction

Assume an array Assume an array aa that is sorted in that is sorted in ascending order, and an item ascending order, and an item XX

We want to write a function that searches We want to write a function that searches for for XX within the array within the array aa, returning the , returning the index of index of XX if it is found, and returning if it is found, and returning -1-1 if if XX is not in the array is not in the array

14-14-2020

Recursive Binary SearchRecursive Binary Search

A recursive strategy for searching a portion of A recursive strategy for searching a portion of the array from index the array from index lolo to index to index hihi is to is to

set set mm to index of the middle portion of array: to index of the middle portion of array:

14-14-2121

mlo hi

Recursive Binary SearchRecursive Binary Search

If If a[m] == X,a[m] == X, we found we found XX, so return , so return mm

If If a[m] > X,a[m] > X, recursively search recursively search a[lo..m-1]a[lo..m-1]

If If a[m] < X,a[m] < X, recursively search recursively search a[m+1..hi]a[m+1..hi]

14-14-2222

mlo hi

Recursive Binary SearchRecursive Binary Search

int bSearch(int a[],int lo,int hi,int X)int bSearch(int a[],int lo,int hi,int X){ { int m = (lo + hi) /2;int m = (lo + hi) /2; if(lo > hi) return -1; // base if(lo > hi) return -1; // base if(a[m] == X) return m; // baseif(a[m] == X) return m; // base if(a[m] > X) if(a[m] > X) return bsearch(a,lo,m-1,X);return bsearch(a,lo,m-1,X); elseelse return bsearch(a,m+1,hi,X);return bsearch(a,m+1,hi,X);}}

14-14-2323

Tower of HanoiTower of Hanoi

• Stack of 64 golden disks, with the largest at the bottom and progressively smaller ones above.

• When the stack is completely moved, the world will come to an end.

• It would take 264−1 (18,446,744,073,709,551,615) moves to finish. At a rate of one move per sec, it would take them roughly 585 billion years to finish.

Tower of HanoiTower of Hanoi

ObjectiveMove the stack of disks from one tower to another with the following rules:•Only one disk may be moved at a time.•Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.•No disk may be placed on top of a smaller disk.

SolutionSolution

N disks

Tower 2Tower 1 Tower 3

Move N – 1 disks from 1 to 2

Move 1 disk from 1 to 3

Demo

Algorithm (n = 3)Algorithm (n = 3)

SolutionSolution

N disks

Tower 2Tower 1 Tower 3

Move N – 1 disks from 1 to 2

Move 1 disk from 1 to 3

Demo

AlgorithmAlgorithm

Move (int n, int from, int to, int aux)Move (int n, int from, int to, int aux) If (n = 1) Then If (n = 1) Then cout << “Move disk from “ cout << “Move disk from “ << from << “ to “ << to << endl << from << “ to “ << to << endl Else Else Move (n – 1, from, aux, to) Move (n – 1, from, aux, to) cout << “Move disk from “ cout << “Move disk from “ << from << “ to << to << endl; << from << “ to << to << endl; Move (n – 1, aux, to, from) Move (n – 1, aux, to, from) End If End If