Question: Java - Data structures P2 (35 points) You can sort a large array of m integers that are in the range 1 to n by
Java - Data structures
P2 (35 points)
You can sort a large array of m integers that are in the range 1 to n by using an array count of n entries to count the number of occurrences of each integer in the array. For example, consider the following array A of 14 integers that are in the range from 1 to 9 (note that in this case m = 14 and n = 9):
9 2 4 8 9 4 3 2 8 1 2 7 2 5
Form an array count of 9 elements such that count[i-1] contains the number of times that i occurs in the array to be sorted. Thus, count is
1 4 1 2 1 0 1 2 2
In particular, count[0] = 1 since 1 occurs once in A. count[1] = 4 since 2 occurs 4 times in A. count[2]=1 since 3 occurs once in A. count[3] =2 since 4 occurs 2 times in A.
Use the count array to sort the original array A. Implement this sorting algorithm in the function
public static void countingSort(int[] a, int n )
and analyze its worst case running time in terms of m (the length of array a) and n.
After calling countingSort(), a must be a sorted array (do not store sorting result in a temporary array).
ArraySort.java
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
