Question: Java - Data structures P3 (35 points) The median of a collection of values is the middle value. One way to find the median is
Java - Data structures
P3 (35 points)
The median of a collection of values is the middle value. One way to find the median is to sort the data and take the value at the center. But sorting does more than necessary to find the median. You need to find only the kth smallest entry in the collection for an appropriate value of k. To find the median of n items, you would take k as n/2 rounded up
You can use the partitioning strategy of quick sort to find the kth smallest entry in an array. After choosing a pivot and forming the subarrays Smaller and Larger, you can draw one of the following conclusions:
If Smaller contains k or more entries, it must contain the kth smallest entry
If Smaller contains k-1 entries, the kth smallest entry is the pivot.
If Smaller contains fewer than k-1 entries, the kth smallest entry is in Larger.
Implement the recursive method
public satic int findKSmallest(int[] a, int k)
that finds the kth smallest entry in an unsorted array a.
Use the method findKSmallest to implement the method
public static int findMedian(int[] a)
that finds the median in an array a.
Java - Data Structures
public class ArraySort { public static
private static
// move pivot to next-to-last position in array swap(a, mid, last - 1); int pivotIndex = last - 1; T pivot = a[pivotIndex];
// determine subarrays Smaller = a[first..endSmaller] // and Larger = a[endSmaller+1..last-1] // such that entries in Smaller are <= pivot and // entries in Larger are >= pivot; initially, these subarrays are empty int indexFromLeft = first + 1; int indexFromRight = last - 2; boolean done = false; while (!done) { // starting at beginning of array, leave entries that are < pivot; // locate first entry that is >= pivot; you will find one, // since last entry is >= pivot while (a[indexFromLeft].compareTo(pivot) < 0) indexFromLeft++; // starting at end of array, leave entries that are > pivot; // locate first entry that is <= pivot; you will find one, // since first entry is <= pivot while (a[indexFromRight].compareTo(pivot) > 0) indexFromRight--; if (indexFromLeft < indexFromRight) { swap(a, indexFromLeft, indexFromRight); indexFromLeft++; indexFromRight--; } else done = true; } // end while // place pivot between Smaller and Larger subarrays swap(a, pivotIndex, indexFromLeft); pivotIndex = indexFromLeft; return pivotIndex; } public static
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
