Chapter 11 Recursion - Purdue...
Transcript of Chapter 11 Recursion - Purdue...
Chapter 11 1
Recursion
Chapter 11
Chapter 11 2
Reminders
• Project 6 is over.• Project 7 has begun
– Start on time!– Not much code for milestone, but a great
deal of thought
Chapter 11 3
Exam 2 Problem Problems
• Problem 2) Be careful about static!
• Problem 4)Be careful about local assignment(Draw pictures if necessary)
• Problem 11)All classes are derived from Object
• Problem 20)Scanner reads text. ObjectInputStream doesn't.
Chapter 11 4
Recursion
• Sometimes a problem can be solved by solving a smaller version of itself.
e.g. Factorial(n) = (n)(n-1)(n-2)...(3)(2)(1) = (n)Factorial(n-1)
Chapter 11 5
Example: Countdown
public void countdown( int number ){ System.out.print( number ); System.out.print( " " ); if ( number > 0 ) countdown( number - 1 );}
What is the result of calling countdown( 10 )?
What happens if the print statements and recursive call are transposed?
Chapter 11 6
Example: Countup
public void countdown( int number ){ if ( number > 0 ) countdown( number - 1 ); System.out.print( number ); System.out.print( " " );}
The placement of the recursive call can have subtle effects.
Chapter 11 7
How Recursion Workscountup( 5 ) countup( 4 ) countup( 3 ) countup( 2 ) countup( 1 ) countup( 0 )
Calls
Sop( 5 + “ “ ) Sop( 4 + “ “ ) Sop( 3 + “ “ ) Sop( 2 + “ “ ) Sop( 1 + “ “ )Sop( 0 + “ “ )
Base Case
Eva
luat
ion
& C
ompl
etio
n
Note:• countup( 5 ) doesn't finish until all of its recursive calls do!• countup( 0 ) doesn't have any recursive calls!
Chapter 11 8
Recursion Guidelines• A recursive method uses an if-else statement.
1)One branch represents a base case which can be solved directly (without recursion).
3)Another branch includes a recursive call to the method, but with a “simpler” or “smaller” set of arguments.
• The recursive calls must move toward the base case
Notice, a loop was not necessary for countdown!
Chapter 11 9
Infinite Recursion
• If the recursive call does not solve a “simpler” or “smaller” case, a base case may never be reached.
• Such a method continues to call itself forever (or until a stack overflow).
• This is called infinite recursion.
Chapter 11 10
Infinite Recursionpublic void countdown( int number ){ System.out.print( number ); System.out.print( " " );// if ( number > 0 ) countdown( number - 1 );}
public void countdown( int number ){ System.out.print( number ); System.out.print( " " ); if ( number > 0 ) countdown( number + 1 );}
Chapter 11 11
Recursion vs. Iteration
• A recursive version of a method is less efficient than the iterative version, but also easier to understand.– (Keep track of the recursive calls and suspended
computations)
• It can be much easier to write a recursive method than it is to write a corresponding iterative method.
Chapter 11 12
Example: Factorialpublic int factorial( int n ){ if ( n > 1 ) return n * factorial( n - 1 ); else return 1;}
Notice that the return value of a recursive call can be used within a recursive method.
Chapter 11 13
Case Study: Binary Search
• Find a number in a sorted array– If found, return the position of the number– If not, return -1
• Could search sequentially, but there is a better way!
Chapter 11 14
Binary Search, cont.
• Because the array is sorted, we can eliminate whole sections of the array as we search.e.g.:Looking for a 7 and we encounter a location
containing a 13, we can disregard from the location containing the 13 through the end
1 2 7 13 34 55
Chapter 11 15
Binary Search, cont.• Other situations to handle:
– Looking for a 7 and we encounter a location containing a 3, we can disregard from the location containing the 3 through the beginning.
– Looking for a 7 and we encounter a location containing a 7, we are finished
1 2 3 7 34 55
Chapter 11 16
Binary Search, cont.
mid = (first + last)/2if (first > last) return -1;
else if (target == a[mid]) return mid;
else if (target < a[mid] search a[first] through a[mid-1]
else search a[mid + 1] through a[last]
first eventually becomes larger than last and we can terminate the search if not found.
Why do we use the middle element?
Chapter 11 17
Binary Search, cont.
Chapter 11 18
Binary Search, cont.
• Each recursive call eliminates about half of the remaining array.
• The number of calls to either find an element or to determine that the item is not present is log n for an array of n elements.
• Thus, for an array of 1024 elements, only 10 recursive calls are needed. (instead of 1024)
Chapter 11 19
Merge Sort• Merge sort takes a “divide and conquer”
approach.
1)The array is divided in halves and the halves are sorted recursively.
2)Sorted subarrays are merged to form a larger sorted array.
Chapter 11 20
Merge Sort, cont.
Pseudocode:
If the array has only one element, stop.
Otherwise Copy the first half of the elements into an array named front.
Copy the second half of the elements into an array named tail. Sort array front recursively. Sort array tail recursively. Merge arrays front and tail.
Chapter 11 21
Merging Sorted Arrays
137
1516
458
1417
Front TailTake the smallest unread element from the “top” of both arrays.
1, 3, 4, 5, 7, 8, 14, 15, 16, 17
01234
Chapter 11 22
Merging Sorted Arrays, cont.• Remove the smaller of the elements from the
beginning of (the remainders) of the two arrays and placing it in the next available position in a larger “collector” array.
• When one of the two arrays becomes empty, the remainder of the other array is copied into the “collector” array.
You “consume” the smallest elements
Chapter 11 23
Merging Sorted Arrays, cont.
int frontIndex = 0, tailIndex = 0, aIndex = 0;while ((frontIndex < front.length) && (tailIndex < tail.length)){
if(front[frontIndex] < tail[tailIndex]} { a[aIndex] = front[frontIndex];
aIndex++; frontIndex++;
}
Chapter 11 24
Merging Sorted Arrays, cont.
else { a[aIndex] = tail[tailIndex];
aIndex++; tailIndex++
}}
Chapter 11 25
Merging Sorted Arrays, cont.
• If either array front or array tail becomes empty, any remaining elements from the other array need to be copied into array a.
• These elements are sorted and are larger than any elements already in array a.
Chapter 11 26
Merge Sort, cont.
Chapter 11 27
Merge Sort, cont.
Chapter 11 28
Merge Sort, cont.