package rebelsky.exam3; import java.util.Comparator; import java.util.Random; import java.util.Vector; import rebelsky.sorting.Sorter; /** * Sort using Quicksort. * * @author Samuel A. Rebelsky * @version 0.1 of November 2004 */ public class Quicksorter implements Sorter { // +--------+-------------------------------------------------- // | Fields | // +--------+ /** * A random number generator used at various points * in the algorithm. */ Random rng; /** * The number of "steps" involved in doing the computation. */ long steps; // +--------------+-------------------------------------------- // | Constructors | // +--------------+ /** * Prepare for quicksorting. */ public Quicksorter() { this.rng = new Random(); } // Quicksorter() // +----------------+------------------------------------------ // | Public Methods | // +----------------+ /** * Get the number of steps counted. */ public long getSteps() { return this.steps; } // getSteps() /** * Reset the number of steps counted to 0. */ public void resetSteps() { this.steps = 0; } // resetSteps() // Documentation is in sorting.Sorter. public void sort(Vector v, Comparator c) throws ClassCastException { sort(v, c, 0, v.size()-1); } // sort(Vector, Comparator) // +-----------------+----------------------------------------- // | Private Methods | // +-----------------+ /** * Sort a subvector of v at positions lb to ub. */ private void sort(Vector v, Comparator c, int lb, int ub) { // Base case: One or fewer elements if (ub <= lb) return; // Normal case // (a) Identify a potential pivot and put it at // position lb. int pivot_pos = lb + rng.nextInt(1 + ub - lb); swap(v, lb, pivot_pos); // (b) Partition the two parts, using the pivot pivot_pos = partition(v, c, v.get(lb), lb, ub); // (c) Put the pivot in the middle. swap(v, lb, pivot_pos); // (d) Sort the two halves sort(v, c, lb, pivot_pos-1); sort(v, c, pivot_pos+1, ub); } // sort(Vector, Comparator, int, int) /** * Partition the values at positions [lb .. ub] so that * (a) all the values at positions [lb ... piv] are less than * or equal to pivot; * (b) all the values at positions [piv+1 .. ub] are greater * than pivot. * * @return piv * The position of the last value less than or equal to pivot. * @pre * The value at position lb is less than or equal to pivot. That is, * c.compare(values.get(lb),pivot) <= 0. * c can be applied to all values in the subvector. * @post * c.compare(v.get(s),pivot) <= 0 for all lb <= s <= piv. * c.compare(v.get(l),pivot) > 0 for all piv < l <= ub. */ private int partition(Vector v, Comparator c, Object pivot, int lb, int ub) { // STUB return lb; } // partition(Vector, Comparator, Object, int, int) /** * Swap elements at positions x and y in vector v. */ private void swap(Vector v, int x, int y) { Object tmp = v.get(x); v.set(x, v.get(y)); v.set(y,tmp); } // swap(Vector, int, int); } // class Quicksorter