Java Chapter 14: Sorting
Consider the minimumPosition method from the SelectionSorter class. Complete the code to write a maximumPosition method that returns the index of the largest element in the range from index from to the end of the array. private static int minimumPosition(int[] a, int from) int minPos = from; for (int i = from + 1; i < a.length; i++) if (a[i] < a[minPos]) { minPos = i; } return minPos; private static int maximumPosition(int[] a, int from) int maxPos = from; for (int i = from + 1; i < a.length; i++) ________________ return maxPos;
(int i =0; i < a.length -1 ; i ++)
The code segment below prints some of the elements in an array with size n. Select an expression to complete the code segment so that the resulting algorithm has O(log n) running time. for __________________________ System.out.println(array[j]);
(int j = 1; j < array.length; j =j *2)
Given the following code snippet for searching an array: int[] arr = {23, 25, 29, 34, 42}; int newVal = 15; int pos = Arrays.binarySearch(arr, newVal); What value will pos have when this code is executed?
-1
The performance of an algorithm is most closely related to what?
...
What is the sequence of values in b after the following code is executed? int[] b = {1, 2, 3, 4, 5}; for (int i = 0; i < b.length; i++) int j = b.length - 1 - i; int temp = b[i]; b[i] = b[j]; b[j] = temp;
1,2,3,4,5
Given int[] list = {5, 1, 6, 4, 2, 7, 3}, what are the contents of list after the partitioning phase of Quicksort if the middle element is chosen as the pivot?
3,1,2,4,6,7,5
An array contains 3, 6, 4, 1, 5, 2, in that order. Selection Sort is used to sort it in ascending order. What is the order of elements after the first three passes (through the outer loop)?
3,2,1,4,5,6
True or false? (a) Both Arrays and Collections classes belong to the java.util package. (b) Arrays has overloaded methods for sorting an array of integers, doubles, or strings. (c) Arrays uses the Selection Sort algorithm for sorting. (d) Arrays has overloaded methods for filling the elements of an array with a given value. (e) All methods in the Arrays class are static.
A)T B)T C)F D)T E)T
Assume that names is an array of String objects that has been initialized with a large number of elements. Select the statement that would sort the elements in names in ascending alphabetic order.
Arrays.sort(names);
The sort method of the Arrays class sorts arrays containing objects of classes that implement the ____ interface.
Comparable
If a call to the Arrays static method binarySearch returns a value of -10, what can be concluded? I the element is not in the array II the element is at index 10 III the element can be inserted at index 9
I and III
Which of the following classes implement the Comparable interface? I Date II Collections III String
I and III
Can you search the following array using binary search? int[] A = {6, 5, 4, 2, 0, 1, -1, -17};
No. Binary search can be applied to a sorted array only
Merge sort is a(n) ____ algorithm.
O (n log (n)
Binary search is an ____ algorithm.
O(log n)
If the array is already sorted, what is the performance of insertion sort?
O(n)
If you implement a recursive linear search, its performance will be ____.
O(n)
In Big-Oh notation, selection sort is a(n) ____ algorithm.
O(n^2)
The largestPosition method below returns the index of the largest element in the tail range of an array of integers. Select the expression that would be needed to complete the selectionSort method below, so that it sorts the elements in descending order. Finds the largest element in the tail range of an array. @param a the array to be searched @param from the first position in a to compare @return the position of the largest element in range a[from]..a[a.length - 1] private static int largestPosition(int[] a, int from) int maxPos = from; for (int j = from + 1; j < a.length; j++) if (a[j] > a[maxPos]) maxPos = j; return maxPos; public static void selectionSort(int[] a) for ____________________________________ int maxPos = largestPosition(a, i); ArrayUtil.swap(a, maxPos, i);
System.currentTimeMillis() - start
The partial linear search method below is designed to search an array of String objects. Select the expression that would be needed to complete the method. public static int search(String[] a, String item) { for (int i = 0; i < a.length; i++) { if ( ____________________________ ) { return i; } return -1; } }
a [i]. equals (item)
The partial binary search method below is designed to search an array of String objects sorted in ascending order. Select the expression that would be needed to complete the method. public static int search(String[] a, int low, int high, String item) if (low <= high) int mid = (low + high) / 2; int result = ____________________________; if (result == 0) return mid; else if (result < 0) return search(a, mid + 1, high, item); else return search(a, low, mid - 1, item); return -1;
a [mid].compareTo(item)
Assume that bands is an ArrayList of String objects which contains a number of elements in ascending order. Select a statement to complete the code segment below, which invokes the Java library binarySearch method to search for the string "Beatles". If the list does not already contain the string, it should be inserted in an appropriate location so that the list remains sorted. int index = Collections.binarySearch(bands, "Beatles"); if (index < 0) __________________________
bands.add(-1-index, "Beatles");
A search technique where, in each step, you split the size of the search in half is called a____ search.
binary
The ____ class contains a sort method that can sort array lists.
collections
If you want to use the Comparable interface, you must implement a single method called ____.
compareTo
A binary search is generally ____ a linear search.
faster than
The merge sort algorithm presented in section 14.4, which sorts an array of integers in ascending order, uses the merge method which is partially shown below. Select the condition that would be needed to complete the method so that the elements are sorted in descending order. private static void merge(int[] first, int[] second, int[] a) int iFirst = 0; int iSecond = 0; int j = 0; while (iFirst < first.length && iSecond < second.length) if (_____________________________) a[j] = first[iFirst]; iFirst++; else a[j] = second[iSecond]; iSecond++; j++; // rest of the method follows here
first [iFirst] > second [ iSecond]
______6) Consider the sort method for selection sort shown below: public static void sort (int[] a) for (int i = 0; i < a.length - 1; i++) int minPos = minimumPosition(i); swap(minPos, i); Suppose we modify the loop control to read int i = 1; i < a.length - 1; i++. What would be the
if (a [i] > a [maxPos] ) { maxPos = i;}
Which of the sorts in the textbook can be characterized by the fact that the best case will have a running time of θ(n) if the data is already sorted? I quicksort II selection sort III insertion sort
insertion sort
Which sort algorithm starts with an initial sequence of size 1, which is assumed to be sorted, and increases the size of the sorted sequence in the array in each iteration?
insertion sort
______14) Consider the following code snippet: public static void sort(int[] a) for (int i = 1; i < a.length; i++) int next = a[i]; int j = i; while (j > 0 && a[j - 1] > next) a[j] = a[j - 1]; j--; a[j] = next; What sort algorithm is used in this code?
insertion sort
The code segment below displays a pattern of asterisks. Select an expression to complete the code segment so that the resulting algorithm has O(n) running time. for (int k = 0; k < n; k++) for _______________________ System.out.print("*"); System.out.println();
int j = 1; j < = 10; j++
In big-Oh notation, suppose an algorithm requires an order of n the number of elements affect the number of visits?
it number of visits goes up by a factor of eight
Assume we are using quicksort to sort an array in ascending order. Into which array location does quicksort's strategy place a pivot element after partitioning?
its final correct location
The following code is an example of a ___ search. public static int search(int[] a, int v) { for (int i = 0; i < a.length; i++) { if (a[i] == v) { return i; } } return -1; }
linear
Which sort algorithm starts by cutting the array in half and then recursively sorts each half?
merge sort
If an element is present in an array of length n, how many element visits, on average, are necessary to find it using a linear search?
n /2
After one iteration of selection sort working on an array of 10 elements, what must hold true?
one element must be corectly placed
Implement an efficient search method for searching an array of strings if a target value is much more likely to be found close to the beginning or to the end of the array, and less likely in the middle of the array.
private static int searcgBothEnds (String [] a, String target) { int i = 0, j = a.length -1;. while (i <=j) { if (target.equals (a[i])) return i; if (target.equals(a[j])) return j; i++; j--; } return -1; }
Suppose you wish to implement the Comparable interface to allow your Vehicle class to compare Auto objects only. Which of the following is the correct way to do this?
public class Vehicle implements Comparable <Auto>
Consider the following class: public class Address implements Comparable<Address> { private String street; private int number; < constructors and methods not shown > } (a) Write a compareTo method for this class. First compare addresses alphabetically by street; if the streets are the same, then compare the numbers. (b) Override Object's equals method in Address in a manner compatible with the compareTo method.
public int compareTo(Address other) { int diff = street.compareTo(other.street); if (diff ==0) diff = number - other.number; return diff; } public boolean equals (Object obj) { if (! obj instanceof Address)) return false; return compareTo ((Address) obj) == 0;
The code below shows a method from the Quicksort class: private static void recursiveSort(double[] a, int from, int to) { if (from >= to) return; int p = (from + to ) / 2; // Partition: int i = from; int j = to; while (i <= j) { if (a[i] <= a[p]) i++; else if (a[j] >= a[p]) j--; else { swap (a, i, j); i++; j--; } } // Place the pivot in its correct position: if ( ____________________________ ) { _______________________________________ ; _______________________________________ ; } else if ( ____________________________________ ) { _______________________________________ ; _______________________________________ ; } // Sort recursively: _________________________________________ ; _________________________________________ ; } Fill in the blanks.
public static void recursiveSort(double [] a, int from, int to) { if (from >= to) return; int p = (from + to) /2; int i =from; int j = to; while (i <= j) { if (a [i] <= a [p]) j--; else { swap (a,i,j); i++ j--; } } if (p <j ) { swap (a,j,p); p =j; } else if (p>i) { swap (a,i,p); p = i; } recursiveSort (a, from, p-1); recursiveSort (a, p+1,to);
Fill in the blanks in the following implementation of Selection Sort: public static void selectionSort(int[] a) { for (int n = ______________________________________ ) { for (int i = _______________________________________ ) { if ( ____________________________________ ) swap( ____________________________________ ); } } } swap(a, i, j) swaps a[i] and a[j].
public static void selestionSort (int [] a) { for (int n = a.length -1; n >0; n--) for (int =0; i <n ; i++) if (a [i] > a [n] swap (a,i,n);
What type of algorithm places elements in order?
sorting
In each iteration, selection sort places which element in the correct location?
the smallest element notyet placed in prior iterations
Consider the sort method shown below for selection sort: public static void sort (int[] a) for (int i = 0; i < a.length - 1; i++) int minPos = minimumPosition(i); swap(minPos, i);
the sort would not consider the first array element
Suppose we modify the loop condition to read i < a.length. What would be the result?
the sort would produce correct results
Consider the sort method shown below for selection sort: public static void sort(int[] a) { for (int i = 0; i < a.length - 1; i++) { int minPos = minimumPosition(i); swap(minPos, i); } }
the sort would work but run one more iteration
The code segment below is designed to add the elements in an array of integers. Select the expression needed to complete the code segment so that it calculates the running time elapsed. long start = System.currentTimeMillis(); int sum = 0; for (int k = 0; k < values.length; k++) sum = sum + values[k]; long runningTime = ____________________________; a) System.currentTimeMillis() b) System.currentTimeMillis() - start c) System.currentTimeMillis() + start d) runningTime + start - System.currentTimeMillis()
the total number of element visits
Assume we are using quicksort to sort an array in ascending order. What can we conclude about the elements to the left of the currently placed pivot element?
they are all less than or equal to the pivot element
Assume we are using quicksort to sort an array in ascending order. What can we conclude about the indexes of two pivot elements placed in consecutive recursive calls?
they are randomly located
Suppose you wish to sort an array list of objects, but the object class does not implement the Comparable interface. Because you are not allowed to modify this class, you decide to provide a comparator object that implements the Comparator interface. Which method must you implement from this interface to achieve your objective?
to compare method