Lab 6 - Sorting

On competing the lab you will:

Eclipse: Data Generation

Create a new project in Eclipse called Lab6Sorting1.

Data Generation

Algorithm Comparison

You know from lectures that the efficiency class of both insertion and selection sort is quadratic for random arrays. Furthermore the running time should increase at a similar rate for larger inputs but insertion should be slightly faster. Prove this using an empirical approach as follows: Using the Insertion and Selection classes from the previous section, develop an executable Java class called SortCompare that contains the following method:

public static double time(String alg, Comparable[] a) {

        double startTime = System.currentTimeMillis();
        if (alg.equals("Insertion"))
            Insertion.sort(a);
        if (alg.equals("Selection"))
            Selection.sort(a);

        return System.currentTimeMillis() - startTime;

    }

Finally, write a main method similar to the following that compares the running time of the two algorithms. You can change the size and number of random arrays (1000 and 100 respectively is manageable but remember these are quadratic algorithms!)

public static void main(String[] args) {

            String alg1 = "Insertion";
            String alg2 = "Selection";

            StdOut.println("Enter the input size of the Date arrays:");
            int n = StdIn.readInt();
            StdOut.println("Enter the number of different inputs to be generated:");
            int k = StdIn.readInt();
            double t1 = timeRandomInput(alg1, n, k); // total for alg1
            double t2 = timeRandomInput(alg2, n, k); // total for alg2
            StdOut.printf("For %d random Dates\n %s is", n, alg1);
            StdOut.printf(" %.1f times faster than %s\n", t2 / t1, alg2);


    }