Download presentation

Presentation is loading. Please wait.

Published byDevin Blake Modified over 3 years ago

1
Chapter 16 Recursion

2
This chapter discusses n Recursion. n Comparison of recursion and iteration. n Recursive solutions using class structure, rather than algorithm design to control recursion.

3
Iteration and recursion n In iteration, the algorithm specifies a step in the solution process that is to be repeated or iterated. n Recursion involves providing a solution to a trivial, base case of the problem, and then designing a solution to the general case by showing how to reduce the general case to one that is a step closer to the base case; the algorithm invokes itself to solve the slightly reduced case.

4
Recursion

5
Recursive selection sort n Base Case: sort a list that is empty or contains only a single element. n General Case: sort a list containing n elements, where n > 1. u Find the smallest element and put it first. u Sort the remaining n-1elements. (This is done by invoking the method itself.) u These self-calls continue until the base case is reached.

6
Selection Sort private void sort (List list, int first, int last, Order compare){ int small // index of smallest if (last > first) { small = smallestOf(list, first, last, compare); interchange(list, first, small); sort(list, first+1,last,compare); }

7
Verification of correctness n Use induction. n The base cases of the induction match the base cases of the algorithm. n The general case of the induction handles the general case of the algorithm.

8
Selection Sort

9
Selection Sort (cont.)

10
n We now have two sets of local variables – one for each invocation of the method sort. n This is like invoking two different methods; the fact that they happen to be invocations of the same method is irrelevant.

11
Selection Sort (cont.)

12

13

14

15

16
Putting this procedure into a Sorter n Provide a public method that calls the recursive method with the appropriate arguments. public class RecursiveSelectionSorter implements Sorter { public void sort (List list, Order compare) { sort(list,0,list.size()-1,compare); } private void sort (List list, int first, int last, Order compare) {…} private int smallestOf (List list, int first, int last, Order compare) {…} private void interchange (list list, int i, int j) {…} }//end of class RecursiveSelectionSorter

17
Putting this procedure into a Sorter (cont.) The method name sort is overloaded. One sort defines the public interface. The other sort is a private "auxiliary" method that does the work.

18
Towers of Hanoi n Move the stack of disks from the starting peg to one of the other pegs, moving only one disk at a time, and without placing a larger disk on top of a smaller disk.

19
Towers of Hanoi (cont.) n We model a move as a class instance. n A move is characterized by the peg a disk is moved from and the peg the disk is moved to.

20
Recursive algorithm for Towers of Hanoi n Base Case: Only one disk to move. n General Case: Move a stack of n disks, where n > 1. n Moving n-1 disks is a step closer to the base case. n We can ignore the largest disk when considering the n-1 smaller disks.

21
Recursive algorithm for Towers of Hanoi (cont.) n Move n-1 disks from the starting peg to the other peg. n Move a disk from the starting peg to the destination peg. n Move n-1 disks from the other peg to the destination peg.

22
Recursive algorithm for Towers of Hanoi (cont.) n The client-server relationship is as follows:

23
Recursive algorithm for Towers of Hanoi (cont.) public class Move A move in the Towers puzzle. Pegs are numbered 1,2,3. public Move (int from, int to) A move of a disk from from to to. public int from () Peg the disk is moved from. public int to () Peg the disk is moved to.

24
Recursive algorithm for Towers of Hanoi (cont.) public void moveTower (int n, int from, int to, SolverObserver o) Report to the specified observer the moves required to move a tower of the specified number of disks, from the specified starting peg to the specified destination peg. require: n >= 1 1 <= from <= 3 && 1 <= to <= 3 from != to public void update (Move m)

25
Recursive algorithm for Towers of Hanoi (cont.) public void moveTower (int n, int from, int to, SolverObserver o) if (n==1) { o.update(new Move(from,to)); } else { int other = 6-from-to //peg that //is not from or to //move n-1 disks to other peg moveTower(n-1,from, other,o); //move big disk to the target o.update(new Move(from,to)); //move n-1 disks to the target moveTower(n-1,other,to,o); }

26
Example: moveDisk(2,1,2,this)

27

28

29
Quick sort n Quick sort typically take on the order of n·log 2 n steps. nn 2 n·log 2 n , ,0001,000,0009,966 10,000100,000,000132, ,00010,000,000,0001,660,964 1,000,0001,000,000,000,00019,931,569 n Quick sort starts by putting one element into position. Rather than positioning the largest or smallest element, quick sort puts an arbitrary element in proper position.

30
Quick sort (cont.) 1. Put an element in its proper sorted position, with smaller elements below an larger elements above. The positioned element is the pivot element. 2. Sort the sub-list of smaller elements below the positioned element. 3. Sort the sub-list of larger elements above the positioned element. n This is clearly recursive!

31
Quick sort (cont.) public class QuickSorter extends Sorter { /** * Sort specified List according to the * specified Order, using quick sort. */ public void sort (List list, Order compare) sort(list, 0,list.size()-1,compare); } /** * Sort list elements first to last */ private void sort (List list, int first, int last, Order Compare) { … }

32
Quick sort (cont.) n Base case: an empty list or a list with a single element. n General Case: handled by the 3 steps mentioned earlier. We separate step 1 out into its own method called partition. partition changes the state of the list like a command, and returns a value like a query.

33
Quick sort (cont.) public int partition (List list, int first, int last, Order compare) Partition list elements indexed first through last for quick sort; return the pivot position. require: 0 <= first < last < list.size() ensure: first <= result <= last for first <= i < result, list.get(i) < list.get(result) for result <= i <= last, list,get(i) >= list.get(result)

34
Quick sort (cont.) n Suppose we chose to put 28 in its proper position. n The method returns value 6, the index of the pivot element.

35
Quick sort (cont.) private void sort (List list, int first, int last, Order compare) { int position;//the pivot index if(first < last) { position = partition(list,first, last,compare); sort(list,first,positions-1,compare); sort(list,position+1,last,compare); }

36
Quick sort (cont.)

37

38

39

40

41

42

43

44

45
private int partition (List list, int first, int last, Order compare) { int pi;//pivot index; int i;//next item of 1 to examine int mid; //middle index: (first+last)/2 Object item; // pivot item mid = (first+last)/2; item = list.get(mid); //put pivot item at end of list interchange(list,mid,last); pi = first; i = first; //havent examined anything //yes=t

46
Quick sort (cont.) /* loop invariant: *for first <= j

47
Quick sort (cont.) When the while loop is reached for the first time, the clauses of the invariant are vacuously true. u Since first == pi == I, there is no value j such that first <= j <= pi and there is no value j such that pi <= j < I. n We select the middle item because in the worst case, the algorithm could take order n 2 time. If the list is ordered (or nearly ordered) and we chose the first or last elements in the list, the order is closer to n 2.

48
Inefficiency n It is often more difficult to design recursive algorithms that are as efficient as iterative algorithms. n Since we control the steps in an iterative process more directly than in a recursive process, inefficiencies often are more obvious in an iterative algorithm.

49
Fibonacci numbers n The sequence of integers beginning with 0 and 1, and in which each successive number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34… public int fib (int n) { if (n ==0) return 0; else if (n == 1) return 1; else return fib(n-1)+fib(n-2) }

50
Fibonacci numbers (cont.) n Each level of recursion duplicates work done at the previous level. n Example: computing fib(6) requires computing fib(5) and fib(4), but the computation of fib(5) also computes fib(4). n The time to compute fib(n) is roughly proportional to fib(n)! n An iterative approach solves the problem in computational time proportional to n.

51
Indirect recursion n A method can invoke itself indirectly. n m1 invokes m2 which invokes m3… which invokes mn which invokes m1.

52
Heads or Tails public char head (String s) The first character of the specified non-empty String. public String tail (String s) A String equal to the specified non- empty String with its first character removed. head(abc) a tail(abc) bc

53
Balanced Parentheses n A function that removes the first balanced substring of parentheses. () ()()()() ()()() ((())) (()()(()()))()(()) ()(())

54
Balanced Parentheses (cont.) public String removeSet (String s) A String equal to the specified String with the first balanced substring of parentheses removed require: s is a balanced string of parentheses private String reduceClosed (String s) A String equal to the specified String with the first substring containing one more closed parenthesis than open parentheses removed. require: s is a string of parentheses that would be balanced if an open parenthesis were appended to the front; in particular, s contains one more closed parenthesis than open parentheses.

55
Balanced Parenthesis (cont.) public String removeSet (String s) { if (s.equals()) return ; else // head(s) is ( return reduceClosed(tail(s)); } private String reduceClosed (String s) { if ( head(s) == ) ) return tail(s); else //head(s) == (;first remove a balanced set. return reduceClosed(removeSet(s));

56
Object recursion n Structural recursion: using object structure in a recursive manner to derive problem solutions. n An object tasked with solving a problem gets assistance from a similar object which solves a simpler instance of the problem.

57
Object recursion (cont.)

58
Odometer n A sequence of digits, in which one digit turning over from 9 to 0 causes its left neighbor to increment. n A solution state is a stable state of the counter, in which all the digits are set. u In the first solution state, all digits are 0. u A next solution state is reached when the counter is incremented by 1. u In the final solution state, all digits are 9.

59
Odometer (cont.) n The solver class is Digit. n The trivial solver class is NullDigit. n Each Digit is responsible for a digit of the solution.

60
Odometer (cont.) n Each Digit has an associate, the Digit to its left. u A Digit extends the solution provided by its associate; a four-digit number, for example, is built by extending a three-digit number. u The right-most Digit in a 1-digit number has a NullDigit associate.

61
Odometer (cont.)

62
n An inner class is a class defined inside another class. n We make AbstractDigit, Digit, and NullDigit inner classes of the DigitCounter.

63
public class DigitCounter { /** * Create a new DigitCounter with the specified number of digits. * require: * digits >= 1 */ public DigitCounter (int digits) { int i; AbstractDigit d = new NullDigit(); for (i = 1; i <= digits; i = i+1) d = new Digit(d); lowDigit = d; } … private AbstractDigit lowDigit ;//right most private abstract class AbstractDigit{…} private class NullDigit extends AbstractDigit{…} private class Digit extends AbstractDigit{ private Digit(AbstractDigit associate) { this.associate = associate; … } … private AbstractDigit associate; // left //neighbor }

64
Odometer (cont.) command:solved:toString: --false -- firsttrue 00 nexttrue 01 nexttrue 02 … nexttrue 99 nextfalse --

65
public class DigitCounter { … /** * Set to all zeros. */ public void first() { lowDigit.first(); } /** * Increment this DigitCounter by 1 */ public void next () { lowDigit.next(); } /** * First or next has been sucessfully performed */ public boolean solved() { return lowDigit.solved(); } /** * Number contained in this DigitCounter * require: * this.solved() */ public String toString() { return lowDigit.toString(); }

66
private AbstractDigit lowDigit ;//right-most private abstract class AbstractDigit { public abstract boolean solved (); public abstract void first(); public abstract void next(); public abstract String toString(); }

67
private class Digit extends AbstractDigit { public Digit (AbstractDigit associate) { this.associate = associate; this.digit = 0; this.solved = false; } public boolean solved () { return solved; } public void first () { associate.first(); if (associate.solved()) { digit = 0; solved = true; } else solved = false; }

68
public void next () { if (digit < 9) { digit = digit + 1; solved = true; } else { associate.next(); if (associate.solved()) { digit = 0; solved = true; } else solved = false; } public String toString () { return associate.toString() + digit; } public AbstractDigit associate () { return associate; } private AbstractDigit associate;//left //neighbor private boolean solved;//a valid number private int digit;//my digit }

69
private class NullDigit extends AbstractDigit { public boolean solved () { return solved; } public void first () { solved = true; } public void next () { solved = false; } public String toString () { return ; } private boolean solved; } n Class NullDigit permits all object entries in the structure to be treated uniformly.

70
Weve covered n Recursive computation u Algorithmic recursion u Object recursion n Indirect recursion n Structural recursion

71
Glossary

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google