Presentation is loading. Please wait.

Presentation is loading. Please wait.

Figures from Chapter 6 of Data Structures via C++ Objects by Evolution

Similar presentations


Presentation on theme: "Figures from Chapter 6 of Data Structures via C++ Objects by Evolution"— Presentation transcript:

1 Figures from Chapter 6 of Data Structures via C++ Objects by Evolution
A. Michael Berman Copyright  1997 Oxford University Press All Rights Reserved

2 Copyright  1997 Oxford University Press All Rights Reserved
Chapter 6 Recursion Overview Using recursion as a problem solving tool. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

3 Copyright  1997 Oxford University Press All Rights Reserved
Chapter Objectives 1. To understand, evaluate, and implement simple recursive functions. 2. To apply recursion to searching and sorting problems. 3. To understand and analyze Quicksort 4. To begin to understand how the computer evaluates recursive programs 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

4 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-1 // cx6-1.cpp // Code Example 6-1: Computing 2 raised to the 5th, without recursion. #include <iostream.h> int twoRaisedTo0() { return 1; } 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

5 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-1 int twoRaisedTo1() { return 2 * twoRaisedTo0(); } int twoRaisedTo2() return 2 * twoRaisedTo1(); int twoRaisedTo3() return 2 * twoRaisedTo2(); 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

6 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-1 int twoRaisedTo4() { return 2 * twoRaisedTo3(); } int twoRaisedTo5() return 2 * twoRaisedTo4(); int main() cout << "2 to the 5th is " << twoRaisedTo5() << "\n"; return 0; 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

7 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-2 // cx6-2.cpp // Code Example 6-2: Recursively computing powers of 2 #include <iostream.h> int twoRaisedTo(int n) { if (n == 0) // special case return 1; else return 2 * twoRaisedTo(n-1); } 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

8 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-2 int main() { cout << "2 to the 5th is " << twoRaisedTo(5) << "\n"; return 0; } 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

9 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-1 When n >= 1 When n = 0 Equation 6-2 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

10 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-3 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

11 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-4 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

12 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-5 Equation 6-6 When n >= 1 When n = 0 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

13 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 6-1 Using Equation 6-6 and substitution, evaluate f(6). 6-2 Use Equation 6-6 to write a program that computes the factorial function. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

14 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-7 Equation 6-8 Total number of sets = sets with “Stairway” + sets without “Stairway” 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

15 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-9 Equation 6-10 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

16 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-11 Equation 6-12 when k = 1 when n = k when n > k and k > 1 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

17 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-3 // cx6-3.cpp // Code Example 6-3: The n choose k function int choose(int n, int k) { if (k == 1) return n; else if (n == k) return 1; else // recursive case: n>k and k>1 return choose(n - 1, k - 1) + choose(n - 1, k); } 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

18 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 6-3 (Exercise for Mathematically Inclined.) Use mathematical induction to prove the equivalence of Equation 6-7 and Equation 6-12. 6-4 In any programming language that uses integers bounded within a fixed range, a straitforward implementation of Equation 6-12 can be used for larger values of n and k than a straightforward implementation of Equation 6-7, Explain. 6-5 Evaluate Equation 6-12 for small values of n and k, say five and two. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

19 Figure 6-1: Visualization of recursive Linear Search
use recursive call linearSearch(a, n-1, target) for this part a[0] through a[n-2] a[n-1] 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

20 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-4 // cx6-4.cpp // Code Example 6-4: Recursive Linear Search int linearSearch(int a[], int n, int target) { // Recursive version of linear search // Precondition: a is an array indexed from 0 to n-1 if (n <= 0) // an empty list is specified return -1; else { 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

21 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-4 if (a[n-1] == target) // test final position return n-1; else // search the rest of the list recursively return linearSearch(a, n-1, target); } // Postcondition: If a value between 0 and n-1 is returned, // a[returnValue] == target; // Otherwise, if -1 is returned, target is not in a 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

22 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 6-6 For an array a = {22, 11, 13, 81, 5}, trace linearSearch(a, 5, 11). 6-7 For an array a = {22, 11, 13, 81, 5}, trace linearSearch(a, 5, 50). 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

23 Copyright  1997 Oxford University Press All Rights Reserved
Algorithm 6-1 Preconditions: a is an array sorted in ascending order, first is the index of the first element to search, last is the index of the last element to search, target is the item to search for. If first > last return failure mid <-(first+last)/2 if a[mid] is equal to target return mid 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

24 Copyright  1997 Oxford University Press All Rights Reserved
Algorithm 6-1 else if target < a[mid] return result of recursive search of a from first upto mid-1 else return result of recursive search of a from mid+1 upto last Postcondition: value returnded is position of target ina, otherwise return failure We can easily turn Algorithm 6-1 into Code Example 6-5. We indicate “failure” by returning the value -1. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

25 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-5 // cx6-5.cpp // Code Example 6-5: Recursive Binary Search int binarySearch(int a[], int first, int last, int target) { // Preconditions: a is an array sorted in ascending order, // first is the index of the first element to search, // last is the index of the last element to search, // target is the item to search for. if (first > last) return -1; // -1 indicates failure of search int mid = (first+last)/2; 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

26 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-5 if (a[mid] == target) return mid; else if (target < a[mid]) return binarySearch(a, first, mid-1, target); else // target must be > a[mid] return binarySearch(a, mid+1, last, target); // Postcondition: Value returned is position of target in a, // otherwise -1 is returned } 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

27 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 6-8 For an array a = {1, 6, 15, 22, 37, 45, 52}, trace binarySearch(a, 0, 6, 37). 6-9 For an array a = {1, 6, 15, 22, 37, 45, 52}, trace binarySearch(a, 0, 6, 40). 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

28 Figure 6-2: Quicksort: The array after one partition step
partition 1: all items <= pivot pivot partition 2: all items > pivot 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

29 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-6 // cx6-6.cpp // Code Example 6-6: Quicksort // Note: this quicksort function depends upon the partition function in cx6-7.cpp int partition(int a[], int first, int last); void quicksort(int a[], int first, int last) { // precondition: a is an array; // The portion to be sorted runs from index first to index last inclusive. if (first >= last) // Base Case -- nothing to sort, so just return return; 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

30 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-6 // Otherwise, we’re in the recursive case. // The partition function uses the item in a[first] as the pivot // and returns the position of the pivot -- split -- after the partition. int split(partition(a, first, last)); // Recursively, sort the two partitions. quicksort(a, first, split-1); quicksort(a, split+1, last); // postcondition: a is sorted in ascending order // between first and last inclusive. } 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

31 Figure 6-3: First attempt at a loop invariant for partition
split last partition 1: all items <= pivot partition 2: all items > pivot items yet to be processed 14 27 22 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

32 Figure 6-4: Better loop invariant for partition
first lastSmall i partition 1: all items <= pivot partition 2: all items > pivot items yet to be processed 27 8 14 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

33 Copyright  1997 Oxford University Press All Rights Reserved
Figure 6-5: Partition example after swapElements update of lastSmall and i 27 14 53 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

34 Figure 6-6: Getting the pivot into its proper location
first lastSmall Exchange a[first] with a[lastSmall] 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

35 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-7 // cx6-7.cpp // Code Example 6-7: Partition function (for quicksort, cx6-6.cpp) void swapElements(int a[], int first, int last); // see Exercise 5-12 int partition(int a[], int first, int last) { int lastSmall(first), i; for (i=first+1; i <= last; i++) // loop invariant: a[first+1]...a[lastSmall] <= a[first] && // a[lastSmall+1]...a[i-1] > a[first] 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

36 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-7 if (a[i] <= a[first]) { // key comparison ++lastSmall; swapElements(a, lastSmall, i); } swapElements(a, first, lastSmall); // put pivot into correct position // postcondition: a[first]...a[lastSmall-1] <= a[lastSmall] && // a[lastSmall+1]...a[last] > a[lastSmall] return lastSmall; // this is the final position of the pivot -- the split index 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

37 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 6-10 For the array a = {17, 22, 91, 11, 4, 50}, trace partition (a, 0, 5). 6-11 For the array a = {11, 21, 19, 44, 56, 51, 95, 45}, trace partition (a, 4, 7). 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

38 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 6-12 For the array a = {72, 19, 25, 26, 19, 44, 91, 88, 11}, trace partition (a, 0, 8). 6-13 Draw a recursion tree to illustrate the operation of Quicksort on the following inputs: 1. A[] = [4,2,3,1,6,5,7] 2. A[] = [7,6,5,4,3,2,1] 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

39 Figure 6-7: Example recursion tree for Quicksort
[67, 58, 38, 81, 90, 57, 54] [54, 58, 38, 57, 67, 81, 90] [54, 58, 38, 57] [81, 90] [38, 54, 58, 57] [81, 90] [38] [58, 57] [] [90] [57, 58] [] [58] 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

40 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-13 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

41 Figure 6-8: A worst case recursion tree for Quicksort
[1,2,3,4,5,6,7] [] [2,3,4,5,6,7] [] [3,4,5,6,7] [] [4,5,6,7] [] [5,6,7] [] [6,7] [] [7] 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

42 Copyright  1997 Oxford University Press All Rights Reserved
Table 6-1 n(as power of 2) n Quicksort Bubble Sort Comparisionsa Comparisons 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

43 Figure 6-9: A best case recursion tree for Quicksort
[4, 1, 3, 2, 6, 5, 7] [2, 1, 3, 4, 6, 5, 7] [2, 1, 3] [6, 5, 7] [1, 2, 3] [5, 6, 7] [1] [3] [5] [7] 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

44 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-14 Equation 6-15 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

45 Copyright  1997 Oxford University Press All Rights Reserved
Figure 6-10: Uniformly distributed pivot splits near the middle half the time n n 3n n 4 2 4 about half the time, the pivot falls in the shaded area around the middle 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

46 Copyright  1997 Oxford University Press All Rights Reserved
Equation 6-16 Equation 6-17 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

47 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 6-14 Create a recursion tree for Quicksort when the input array is [7,6,5,4,3,2,1], that is, in reverse-sorted order. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

48 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 6-15 As we saw above, if the partition function always picks the first element as the pivot, then a sorted or reverse-sorted list yields the worst-case. In many situations, the sorted or reverse-sorted list may come up more often than you would expect if the orders are random, so you could argue that it’s a bad idea to pick the first element as the pivot. Instead, you could pick the middle element-a[(last - first)/2]. Trace the operation of a Quicksort with the pivot chosen as the middle element to verify that a reverse-sorted list no longer results in worst-case performance. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

49 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 6-16 Picking the middle element as the pivot, as discussed in Exercise 6-15, eliminates the reversed-sorted list as the worst case, but there still exists a O(n2) worst-case input. Show an input of size seven that has worst-case performance when picking the middle element. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

50 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 6-17 Suppose you pick the pivot at random, rather than picking it from a fixed position. Then as long as all the input elements are distinct, that is, none of the integers occurs more than once, there does not exist any input that will always result in the worst-case performance. After all, a “randomized” algorithm will behave differently each time. Modify the partition function to create a Randomized Quicksort. Can you see any disadvantage to this approach? 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

51 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 6-18 The strategy discussed in Exercise 6-17 works to prevent the worst-case when all elements are distinct. However, suppose that the input consists of an array all containing the same number. Can you suggest a modification in Quicksort that will prevent poor performance in this case? 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

52 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-8 // cx6-8.cpp // Code Example 6-8.cpp: function calls int a(int x) { return x+x; } int b(int x) int z(x + 3); int y(a(z)); // *** z = x * y; return z; 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

53 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 6-9 // cx6-9.cpp // Code Example 6-9: Recursive function call int f(int x) { int y; if (x == 0) return 1; else { y = 2 * f(x-1); return y + 1; } 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

54 Figure 6-11: Execution of Code Example 6-9 for f(3)
copy of f x = 3 y = ? call f(2) copy of f x = 2 y = ? call f(1) copy of f x = 1 y = ? call f(0) copy of f x = 0 y = ? return 1 y = 2 * 1 = 2 return y + 1 = 3 y = 2 * 3 = 6 return y + 1 = 7 y = 2 * 7 = 14 return y + 1 = 15 value returned by call is 15 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

55 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 6-19 Trace Code Example 6-9 for the call f(4). 6-20 Find a closed-form expression for the function f in Code Example 6-9. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

56 Copyright  1997 Oxford University Press All Rights Reserved
Chapter Summary A recursive solution to a problem is stated in terms of a smaller version of the same problem and a non-recursive base case Functions can be defined by recursive definitions, which can be translated directly into recursive programs. Recursion can be used to create linear search and binary search algorithms. Quicksort is a recursive sorting algorithm with O(nlogn) average-case performance. Compilers implement recursive function calls in much the same way the implement non-recursive ones. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

57 Programming Laboratory Problems
6-1 Modify the recursive binarySearch function so that each time it’s called it prints out the values of first and last. Create a driver that creates a large (at least 10,000 element) array of ints and calls your modified binarySearch. Try searching for targets in the list, and targets not in the list. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

58 Programming Laboratory Problems
6-2 Add code to Quicksort to keep track of the number of comparisons, and write a driver that calls Quicksort with random date. Build a table of the comparisons performed by Quicksort, similar to the one shown as Table 6-1 on Page How do your results compare with mine? Graph the number of comparisons. How does your graph compare to the predicted average performance of Quicksort? 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

59 Programming Laboratory Problems
6-3 Using the Timer class5 and your driver, experiment with the recursive and non-recursive versions of Binary Search on your system. You should use a fairly big list (say, 10,000 items) and a reasonable number of searches (say, 1,000). How does the relative performance of the two searches compare? 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

60 Programming Laboratory Problems
6-4 The MergeSort algorithm sorts an array with O(nlogn) worst-case performance. (For a proof, see an algorithms book such as Cormen-Leiseron-Rivest.) MergSort consists of two parts: 1. A recursive part that breaks the array into two subparts, makes recursive calls to sort each of the two subparts, and then calls a merge function to merge them back together: 2. A merge, that takes two sorted subarrays an merges them into a single sorted array. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

61 Copyright  1997 Oxford University Press All Rights Reserved
Algorithm 6-2 Mergesort MergeSort(a, first, last) Precondition: Input is an array, a, and two indices first and last if (first >=last) then there’s nothing left to be sorted, so just return else mid = (first + last)/2; MergeSort(a, first, mid) MergeSort(a, mid+1, last) Merge(a, first, mid, last) (continued on the next slide) 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

62 Copyright  1997 Oxford University Press All Rights Reserved
Algorithm 6-2 Mergesort Postcondition: Array a is sorted from index first to last To sort an array of n elements, you call: MergeSort(a, 0, n-1). To complete the MergeSort project: 1. Write a Merge function with the folowing specification: void merge(int a[], int first, int mid, int last) Precondition: a is an array with the items from first up to mid sorted, and the items from mid + 1 up to last are sorted. Postcondition: apost contains the same items from apre is sorted from first up to last. (continued on the next slide) 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

63 Copyright  1997 Oxford University Press All Rights Reserved
Algorithm 6-2 Mergesort Note that there may be other parts of the array between 0 and first-1, and between last+1 and the end of the array, but the merge function should leave these elements undisturbed. For example, suppose a = [1,3,6,2,8,9], first=0, and mid=2. Then after calling merge, a = [1,2,3,6,8,9]. 2. Write a test plan for merge, and a driver, and test your merge function thoroughly. (continued on the next slide) 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

64 Copyright  1997 Oxford University Press All Rights Reserved
Algorithm 6-2 Mergesort 3. Write the mergeSort function: void mergeSort(int a[], int first, int last) 4. Write a test plan for mergeSort, and a driver, and test your mergeSort function thoroughly. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

65 Programming Laboratory Problems
6-5 Write a recursive function, binPrint, whith the following specifications: void binPrint(int I, int length) Precondition: I is an integer whose binary representation is length digits long. Postcondition: None Side Effect: Prints the binary representation of I, including leading zeroes. (Continued on next slide) 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

66 Programming Laboratory Problems
For example, binPrint(14, 5) would print out: Using the following observations to create the recursive function--if length == 0, then you do nothing. If length > 0, then if you first print out the results of binPrint(1/2, length -1), and then print either a 0 or 1 depending on the last digit in I. For example, using binPrint(14, 5), you first (recursively) print binPrint(7, 4), which is 0111, and then print, in this case, a 0. Write the binPrint function, a test plan, and a test driver , and test your binPrint function thoroughly. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

67 Programming Laboratory Problems
6-6 A Gray Code is a sequence of binary numbers in which each number differs in exactly one digit from the number before it. For example, a Gray Code of size 3 is: 000, 001, 011, 010, 110, 111, 101, You can write a recursive program for computing Gray Codes by using the following observations: A Grey Code of size 1 is 0, 1. A Grey Code of size I can be computed by first computing a Gray Code of size I - 1, and then adding first a 0 to the beginning of each number, then a 1 to the beginning of (Continued on next slide) 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

68 Programming Laboratory Problems
Each number. For example, a Grey Code of size 2 is: 00 01, 11, 10. To get the Grey Code of size 3, you first add a 0 to the front of each item, giving 000, 001, 011,010, and then a 1, giving 100, 101, 111, You can see this gives you the Gray Code of size 3 that’s found above. Write a function greyCode with the following specification: void grayCode(int a[], int n) Precondition: None. Postcondition: a contains the items in a Gray Code of length n. (Continued on next slide) 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

69 Programming Laboratory Problems
Write the greyCode function, and a driver. The driver has to allocate an array big enough to store the final result; a Gray Code of length n has 2n items. Note that the results are ints, so if you simply print them out you won’t see them in binary. If you have a binPrint function such as described in the last project, you can use it to print the results in binary. 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

70 Programming Laboratory Problems
6-7 The Towers of Hanoi puzzle consists of a set of graduated disks and tree pegs, as shown in Figure The goal is to move all the disks from peg 1 to peg 3, using peg 2 as necessary, and without ever putting a larger peg on top of a smaller peg. (Continued on next slide) 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

71 Programming Laboratory Problems
The recursive algorithm works like this. First, move every disk except the largest from peg 1 to peg 2 (using the same recursive algorithm, but for a smaller problem). Then, move the largest disk to peg 3. Now, again using the recursive algorithm, move all the disks from peg 2 to peg 3. Write the following function: void towers(int n, int fromPeg, int toPeg) that prints out the moves required to move n disks from the fromPeg to the to Peg. (Continued on next slide) 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

72 Figure 6-12: The Towers of Hanoi, initial configuration
3 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved

73 Programming Laboratory Problems
For example, towers(1, 1, 2) will print: move disk from peg 1 to peg 2 and towers(3, 1, 3) will print: move disk from peg 1 to peg 3 move disk from peg 3 to peg 2 move disk from peg 2 to peg 1 move disk from peg 2 to peg 3 5/27/2019 Copyright  1997 Oxford University Press All Rights Reserved


Download ppt "Figures from Chapter 6 of Data Structures via C++ Objects by Evolution"

Similar presentations


Ads by Google