next up previous
Next: Implement a heap Up: Assignment 9: Heaps Previous: Clean up the sorters

Clean up the sorters

  1. Dig out your old implementation of mergesort and selection sort and copy them into a class called Sort. Modify both methods so that they take an array of ints as a parameters and return a reference to a sorted array of ints.
  2. Write a main in Sort.java that creates an array of random ints, sorts the array, and prints the result.

    You can use randInt to generate the random numbers:

        public static int randInt (int low, int high) {
            while (true) {
                int x = (int)(Math.random() * (high-low+1) + low);
                if (x >= low && x <= high) return x;
            } 
        }
    You can also use a command-line argument to control which sort algorithm the program uses. When you run a program using the Java run-time system, the words you type after the name of the startup class get put into the array of Strings that is passed to main. For example, I wrote the following in main:

            if (args[0].charAt(0) == 'm') {
                a = mergeSort (a);
            } else {
                a = selectionSort (a);
            }
    Then at the UNIX prompt I can write java Sort selection or java Sort merge and it uses the specified sort algorithm.
  3. In Linux, there is a command called time that executes a program and then reports how long it took. We will use it to compare the run-times of the sort algorithms. First, comment out the line that prints the contents of the array. Then try:

    % javac Sort.java
    % time java Sort s
    % time java Sort m
    On my machine, the output is

    8.110u 0.070s 0:08.18 100.0%    0+0k 0+0io 2109pf+0w
    The first number is ``user time,'' the second is ``system time,'' and the third number is what we want, elapsed time in minutes and seconds.
  4. Run your program with a range of array sizes (maybe from 1000 to 5000 by thousands) and record the run times for both selection sort and mergesort. Make a graph that shows the two curves, run-time versus problem size.



Allen Downey
Mon Nov 13 09:09:05 EST 2000