import java.util.Random; /* An instance of this class can sort an array of type int[] (or a segment ** thereof) into ascending order. ** ** Author: R. McCloskey ** Date: Oct. 2018 */ public class QuickSorterOfInt { // instance variables // ------------------ private Random rand; // for choosing pivots pseudo-randomly private PivotPartitionerOfInt p; // to partition array segments // constructor // ----------- public QuickSorterOfInt() { rand = new Random(); } // observers // --------- /* Returns the # of swaps (of array elements) that were performed ** during the most recent call to sort(). */ public int swapCount() { return p.getSwapCount(); } /* Returns the # of comparisons (of array elements to pivot values) ** that were performed during the most recent call to sort(). */ public int compareCount() { return p.getCompareCount(); } // sort() methods // -------------- /* Rearranges the elements of the given array so that they are in ascending ** order, using one version of C.A.R. Hoare's QuickSort algorithm. */ public void sort(int[] a) { sort(a, 0, a.length); } /* Rearranges the elements of the given array segment (a[low..high)) ** so that they are in ascending order. Based upon C.A.R. Hoare's ** QuickSort algorithm. */ public void sort(int[] a, int low, int high) { p = new PivotPartitionerOfInt(a); // to perform partitioning within a[] sortAux(a, low, high); } // private methods // --------------- /* Auxiliary method in which the sorting takes place. ** pre: p != null (i.e., the object that partitions has been created) */ private void sortAux(int[] a, int low, int high) { if (high - low < 2) { // segment to be sorted has length <= 1, so there is nothing to do } else { // choose the location of the pivot (within the segment to be // sorted) pseudo-randomly using rand int pivotLoc = low + rand.nextInt(high-low); // partition a[low..high) with respect to the chosen pivot. p.partition(low, high, a[pivotLoc]); // recursively sort the <-pivot and >-pivot segments int eqStart = p.getEqStartLoc(); int gtStart = p.getGtStartLoc(); sortAux(a, low, eqStart); sortAux(a, gtStart, high); } } // main() method for testing public static void main(String[] args) { int[] ary = new int[] { 45, 3, -3, 0, 15, 34, 19, -9, 57, 2, 5, 0, 18 }; System.out.println("Array before sorting:"); printIntArray(ary); QuickSorterOfInt qSorter = new QuickSorterOfInt(); qSorter.sort(ary); System.out.println("\nArray after sorting:"); printIntArray(ary); System.out.println("# swaps during sorting: " + qSorter.swapCount()); System.out.println("# comparisons during sorting: " + qSorter.compareCount()); } private static void printIntArray(int[] a) { for (int i=0; i != a.length; i++) { System.out.print(a[i] + " "); } System.out.println(); } }