Download presentation
Presentation is loading. Please wait.
1
Recursion: The Mirrors
Chapter 2
2
Recursive Solutions Recursion breaks problem into smaller identical problems An alternative to iteration A recursive solution
3
Recursive Solutions A recursive function calls itself
Each recursive call solves an identical, but smaller, problem Test for base case enables recursive calls to stop Eventually, one of smaller problems must be the base case Recursion and looping have the same computational power
4
Recursive Solutions EX: Factorial
Fact( n) = 1, if n = 0 = n * Fact(n-1), if n > This is an example of a recurrence relation Questions for constructing recursive solutions How to define the problem in terms of a smaller problem of same type? How does each recursive call diminish the size of the problem? What instance of problem can serve as base case? As problem size diminishes, will you reach base case?
5
A Recursive Valued Function: The Factorial of n
An iterative solution A recursive solution Note: Do not use recursion if a problem has a simple, efficient iterative solution
6
A Recursive Valued Function: The Factorial of n
Box Trace
7
The Box Trace Label each recursive call
Represent each call to function by a new box Draw arrow from box that makes call to newly created box After you create new box executing body of function On exiting function, cross off current box and follow its arrow back
8
The Box Trace The beginning of the box trace A box
9
The Box Trace Box trace of fact(3)
10
The Box Trace Box trace of fact(3)
11
The Box Trace Box trace of fact(3)
12
Writing an Array’s Entries in Backward Order?
The function writeArrayBackward
13
The Binary Search of a Sorted Array – algorithm?
Consider details before implementing algorithm: How to pass half of anArray to recursive calls of binarySearch ? How to determine which half of array contains target? What should base case(s) be? How will binarySearch indicate result of search?
14
The Binary Search Box trace of binarySearch with anArray = <1, 5, 9, 12, 15, 21, 29, 31>: (a) a successful search for 9;
15
The Binary Search Box trace of binarySearch with anArray = <1, 5, 9, 12, 15, 21, 29, 31>: (b) an unsuccessful search for 6
16
Binary Search Code void recBinarySearch (ArrayType a, int first, int last, ElementType item, bool & found, int & loc) /* Pre: Elements of a are in ascending order; item has the same type as the array elements Post: found = true and loc = position of item if search is successful; otherwise, found is false */ { if (first > last) // anchor 1 -- empty sublist found = false; else // inductive case { loc = (first + last) / 2; if (item < a[loc]) // the first half recBinarySearch( a, first, loc-1, found loc); else if (item > a[loc]) // the second half recBinarySearch (a, loc + 1, last, found, loc); else found = true; // anchor 2 -- found item } }
17
A Bad Use of Recursion (Multiplying Rabbits)
Fibonacci numbers 1, 1, 2, 3, 5, 8, 13, 21, 34 f1 = 1, f2 = 1 … fn = fn -2 + fn -1 A recursive function unsigned long Fib (unsigned n) /* Pre: n > 0 Post : if n > 0, returns nth fibonacci number, else returns error code */ { if (n <= 2) return 1; return Fib (n – 1) + Fib (n – 2); }
18
A Bad Use of Recursion Why is this inefficient? Note the block trace
19
Iterative Fibonacci /* Pre: n > 0 Post : if n > 0, returns nth fibonacci number, else returns error code */ unsigned long fib( unsigned int n ) { unsigned long k, f1, f2; if ( n < 2 ) return n; else { f1 = f2 = 1; for(k = 2; k <n; k++) { f = f1 + f2; f2 = f1; f1 = f; } return f;
20
Palindrome Checker – activity
#include <iostream> #include <string> using namespace std; bool palChecker(const string &s, int first, int last); int main() { string palindrome = "able was I ere I saw elba"; //string palindrome = ""; //string palindrome = "foobar"; palChecker(palindrome, 0, palindrome.length() -1) ? cout<< " Is a palindrome. \n" : cout<< " Is not a palindrome. \n”; } bool palChecker(const string &s, int first, int last){ /* Precondition: none Postcondition : returns true iff s = sR */ if(first > last) return true; if(s[first] != s[last]) return false; return palChecker(s, first + 1, last - 1);}
21
The Towers of Hanoi The problem statement Solution Task
Move disks from left peg to right peg When disk moved, must be placed on a peg Only one disk (top disk on a peg) moved at a time Larger disk may never be placed on a smaller disk The problem statement Beginning with n disks on pole A and zero disks on poles B and C, solve towers(n, A, B, C) . Solution With all disks on A, solve towers(n – 1, A, C, B) With the largest disk on pole A and all others on pole C, solve towers(n – 1, A, B, C) With the largest disk on pole B and all the other disks on pole C, solve towers(n – 1, C, B, A)
22
The Towers of Hanoi Hand trace the recursive solution with 3 and 5 disks, use in Safari. Examine solveTowers.cpp – Chapter 2, section 2.5 on web site Move top disk from pole A to pole C Move top disk from pole A to pole B Move top disk from pole C to pole B Move top disk from pole B to pole A Move top disk from pole B to pole C
23
The Towers of Hanoi The order of recursive calls that results from solveTowers(3, A, B, C)
24
Choosing k Out of n Things-skip
A Combinatorial method This example of a recursive solution comes from the field of Combinatorics Problem: A D.J. plays 10 songs each hour. There are 40 different songs. How many different one hour sets are possible? Or in general given 40 different things, how many sets of size 10 can be chosen Or using the standard notation – n choose k
25
N choose K From 5 choose 2 Consider a simpler problem, from 5 letterschoose 2, ABCDE All the sets with A (from 4 choose 1): AB AC AD AE Those without A (from 4 choose 2, no A): BC BD BE CD CE DE Or, in general, we get
26
N choose K Rewritten as a function named c that has two parameters n and k: We're getting closer but where is the base case?
27
N choose K base cases cont.
The base cases for n choose k First, n must be at least as big as k: We cannot choose a 10 song set from 9 songs When n == k, there is only one possible 10 song set from 10 songs To be meaningful, k must be at least 1 We're not interested in sets with 0 songs When k is 1, there are n ways to choose If we only play 1 song set, and we have 10 songs to choose from, we get n, or 10, possible sets
28
N choose K Finally, here is the recursive definition of n choose k
The recursive definition of n choose k summarizes all of these points: What is c(5, 2)? ____________ What is c(4, 1)? ____________ What is c(4, 2)? ____________ What is c(6, 3)? ____________
29
Choosing k Out of n Things
Function for recursive solution.
30
Choosing k Out of n Things
The recursive calls that g (4, 2) generates
31
Recursion and Efficiency
Factors that contribute to inefficiency Overhead associated with function calls Some recursive algorithms inherently inefficient Keep in mind Recursion can clarify complex solutions … but … Clear, efficient iterative solution may be better
32
End Chapter 2
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.