package rebelsky.sorting; import java.util.Comparator; import java.util.Random; import java.util.Vector; import rebelsky.io.Pen; /** * Test a particular sorter. * * @author CSC152 2004F. */ public class SorterTester { /** * The sorter we are to test. */ Sorter s; /** * Our friendly integer comparator. */ Comparator iic; /** * Create a new tester for a particular sorter. */ public SorterTester(Sorter _s) { this.s = _s; this.iic = new IncreasingIntegerComparator(); } // SorterTester(Sorter) /** * For those who want to see results, show a test of sorting * n randomly selected integers. */ public void printedTest(Pen p, int n) { Vector v = new Vector(n); Random r = new Random(); for (int i = 0; i < n; i++) v.add(i, new Integer(r.nextInt(199)-99)); p.println("Original random vector: " + v); this.s.sort(v, this.iic); p.println("Sorted vector: " + v); } // printedTest() /** * Perform a simple test on the sorter. */ public boolean simpleTest() { // Create a vector Vector v = new Vector(6); v.setSize(6); v.set(0, new Integer(22)); v.set(1, new Integer(6)); v.set(2, new Integer(6)); v.set(3, new Integer(7)); v.set(4, new Integer(1)); v.set(5, new Integer(2)); // Sort it using the sorter this.s.sort(v, this.iic); // Verify that it is now in order for (int i = 1; i < v.size(); i++) { if (this.iic.compare(v.get(i-1),v.get(i)) > 0) return false; } // for return true; } // simpleTest(Sorter) /** * Test a vector of size n that is exactly backwards. * * @exception Exception * If sorting fails. */ public void backwardsTest(int n) throws Exception { // Build a standard vector. Vector v = standardVector(n); // Reverse it. for (int i = 0; i < n/2; i++) swap(v,i,n-i-1); // Sort the vector this.s.sort(v,this.iic); // Check that it contains the right values checkStandard(v); } // backwardsTest(int) /** * Create a "standard" vector of size n. For now, I use odds from 1. * to 2*n-1 */ private Vector standardVector(int n) { Vector v = new Vector(n); v.setSize(n); // Create the vector of odds in decreasing order [....,5,3,1] for (int i = 0; i < n; i++) v.set(i, new Integer(2*i+1)); return v; } // standardVector(int) /** * Determine whether a vector meets the standard. (If it does, * sorting usually worked correctly.) */ private void checkStandard(Vector v) throws Exception { int n = v.size(); for (int i = 0; i < n; i++) { if (((Integer) v.get(i)).intValue() != 2*i+1) throw new Exception("Result was: " + v); } // for } // checkStandard(Vector) public 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 SorterTester