10
play

10 Chapter Exercises Searching and Sorting 10.1. Consider the - PDF document

Solutions to 10 Chapter Exercises Searching and Sorting 10.1. Consider the following array of sorted integers: 0 1 2 3 4 5 6 7 8 9 10 11 10 15 25 30 33 34 46 55 78 84 96 99 Using the binary search algorithm, search for 23


  1. Solutions to 10 Chapter Exercises Searching and Sorting 10.1. Consider the following array of sorted integers: 0 1 2 3 4 5 6 7 8 9 10 11 10 15 25 30 33 34 46 55 78 84 96 99 Using the binary search algorithm, search for 23 . Show the sequence of array elements that are compared, and for each comparison, indicate the values for low and high . low high mid compare 0 11 5 23 < num[5] 0 4 2 23 < num[2] 0 1 0 23 > num[0] 1 1 1 23 > num[1] 2 1 low > high, so stop. Not found. 1

  2. 2 Solutions to Chapter 10 Exercises 10.2. We assumed all elements in an array are distinct, that is, there are no du- plicate values in the array. What will be an effect to the linear search algo- rithm if an array contains duplicate values? If the array contains duplicate values, then the linear search will return the value that is stored in the first position, i.e., the smallest index. A new search routine must written to return the positions for all duplicate val- ues. 10.3. Will the sorting algorithms presented in this chapter work if the unsorted array contains any duplicate values? Yes, duplicate values will not cause any problem. 10.4. In this chapter we analyzed sorting algorithms by counting the number of comparisons. Another possible method for analyzing the algorithms is counting the number of data exchanges. How many data exchanges do the selection and bubble sort make in the worst case? Regardless of the origi- nal list, the selection sort will make the same number of data exchanges. However, the number of data exchanges the bubble sort makes depends on the arrangement of elements in the original list. In the case of selection sort, the total number of data exchanges is N-1, the same number as the number of passes because selection sort performs one data exchange after every pass. In the case of bubble sort, the total number of data exchanges in the worst case is equal to the total number of comparisons. In other words, in the worst case, every comparison will result in a data exchange. This situa- tion happens when the original array is the reverse order (i.e., sorted in descending order). We already know the total number of comparisons (== the total number of data exchanges) in the worst case is N – 2 ∑ ( ) N ( ) N – 2 – 1 N 2 ( ) ( ) … ≅ N – 2 + N – 1 + + 1 = i = - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2 i = 1 10.5. Another simple sorting algorithm is called an insertion sort . Suppose we have a sorted list of N elements and we need to insert a new element X into this list to create a sorted list of N +1 elements. We can insert X at the

  3. Solutions to Chapter 10 Exercises 3 correct position in the list by comparing it with elements list[ N − 1], list[ N − 2], list[ N − 3], and so forth. Every time we compare X and list[i], we shift list[i] one position to list[i+1] if X is smaller than list[i]. When we find list[i] that is smaller than X , we put X at position i +1 and stop. We can ap- ply this logic to sort an unordered list of N elements. We start with a sort- ed list of one element and insert the second element to create a sorted list of two elements. Then we add the third element to create a sorted list of three elements. Figure FIGURE 10.18 illustrates the steps in the insertion sort. FIGURE 10.18 Steps in an insertion sort. unsorted sorted 0 1 2 3 4 5 6 7 8 23 17 5 90 12 44 38 84 77 1 insert 17 0 1 2 3 4 5 6 7 8 17 23 5 90 12 44 38 84 77 2 insert 5 0 1 2 3 4 5 6 7 8 3 5 17 23 90 12 44 38 84 77 insert 90 and so on ... Write a method that implements the insertion sort algorithm. You may simplify the method by sorting only integers.

  4. 4 Solutions to Chapter 10 Exercises Answer: public void insertionSort( int[] number ) { //one execution of the outer loop is one pass for (int endIndex = 1; endIndex < number.length; endIndex++) { value = number[endIndex]; index = endIndex - 1; //if the current element at index is larger //than value, then shift down the element while (index >= 0 && number[index] > value) { number[index+1] = number[index]; index--; } //move the value to the correct position number[index+1] = value; } } 10.6. Analyze the insertion sort algorithm of exercise 5 by counting the number of comparisons and data exchanges. Provide the analysis for the worst case. The worst case occurs, as was the case with bubble sort, when the origi- nal list in the reverse order (i.e., descending order). In this case, each comparison will result in one data movement. We also have one final data movement to move the current value into the correct position. The total number of comparisons in the worst case is N – 1 ( ) N ∑ N – 1 N 2 ( ) ( ) … ≅ N – 1 + N – 2 + + 1 = i = - - - - - - - - - - - - - - - - - - - - - - 2 i = 1

  5. Solutions to Chapter 10 Exercises 5 The number of data movements for each pass is one more than the number of comparisons for the pass, so the total number of data movements in the worst case is N ( ) ∑ N N + 1 N 2 ( ) ( ) … ≅ - - - - - - - - - - - - - - - - - - - - - - N + N – 1 + + 2 = i = – 1 2 i = 2 Notice that we are couting the data movement ( one assignment) and not the data exchanges (three assignments). 10.7. Write a test program to compare the performances of selection sort, bub- ble sort, and heapsort algorithms experimentally. Use the random method from the Math class to generate 1000 integers and sort the generated inte- gers using the three sorting algorithms. For each execution, record the time it took to sort the numbers. You can use the Clock class from the jav- abook package to record the execution time. For example, Clock myClock = new Clock( ); myClock.start( ); //starts the clock //sort the integers myClock.stop( ); //stops the clock //record the elaspsed time double elaspedTime = myClock.getElapsedTime( ); 10.8. Consider the following property about the bubble sort: • If the last exchange made in some pass occurs at the J th and (J +1 ) st positions, then all elements from the (J +1 ) st to the N th positions are in their correct location. Rewrite the bubble sort algorithm using this property. See Exercise10_8.java. 10.9. The Heap class given in Section 10.3 sorts only the integers. Improve the class by making it possible to sort any objects that recognize the compare- To method, which is described in Section 10.4, so the new Heap class will be able to sort Person , Integer , Double , and String objects among others.

  6. 6 Solutions to Chapter 10 Exercises Since the elements in the internal array can be any object, declare an array of Object objects. All Java classes are automatically a subclass of Object , unless they are declared explicitly as a subclass of another class. The dec- laration of heap will be like private Object[ ] heap; and the setData method will be like public void setData( Object[ ] data ) { heap = new Object[ data.length ]; sortedList = new Object[ data.length ]; for (int i = 0; i < data.length; i++ ) { heap[i] = data[i]; } } 10.10. In the Heap class, we used two separate arrays: one for the heap and an- other for the sorted list. It turns out we can do everything with just one ar- ray. Notice that the heap will decrease in size by one element after every rebuild step. The unused space at the end of the heap array can be used to store the sorted list. Modify the Heap class so it will use only one array. See Exercise10_10.java. Note: There’s a logical error in the extract method. The method will work correctly because two separate arrays are used, but logically, the correct extract method should be like this (changed parts are highlighted in bold): private void extract( ) { int current, maxChildIndex; boolean done; for (int size = heap.length-1; size >= 0; size--) { //remove the root node data sortedList[size] = heap[ 0 ]; //move the last node to the root

  7. Solutions to Chapter 10 Exercises 7 heap[ 0 ] = heap[size]; //rebuild the heap with one less element current = 0; done = false; while ( !done ) { if ( 2*current+1 >= size ) { //current node has no children, so stop done = true; } else { //current node has at least one child, //get the index of larger child maxChildIndex = maxChild( current, size-1 ); if ( heap[current] < heap[maxChildIndex] ) { //a child is larger, so swap and continue swap( current, maxChildIndex ); current = maxChildIndex; } else { //value relationship constraint //is satisfied, so stop done = true; } } } testPrint( size ); //TEMP } } This updated extract method is used in the solution. The position size should not be considered further because the value in this position is not a part of rebuild process. Without this modification, the solution with a sin- gle array will not work properly. 10.11. Modify the Heap class by defining a separate method called rebuild , which will be used by both the construct and extract methods. 10.12. In Section 10.4, we implemented the sorting routine for the AddressBook class with the bubble sort algorithm. Modify the sorting routine by using the Heap class of exercise 9. 10.13. Instead of maintaining an unsorted list and returning the sorted list when the sort method is called, modify the AddressBook class so that it main-

  8. 8 Solutions to Chapter 10 Exercises tains the sorted list of Person in alphabetical order. Modify the seach rou- tine by using the binary search algorithm.

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend