CSci 160 Lab 9:
Tuning Quicksort and Comparing it With Other Algorithms

Objectives

To find the "optimal" cutoff for quicksort and see how it compares with the run-time of other sorting algorithms.

Exercises

  1. Start by downloading the following files: Put them all in the same BlueJ project.
  2. Unlike lab 6, we'll really be interested in the bottom line here. Not numbers of swaps, not comparisons, but.... time! The simplest way to time a Java method, as we saw in Lab 3, is to surround it with this code:
                time = (double) ( System.currentTimeMillis( ) );
                //whatever it is you want to time
                time = (double) ( System.currentTimeMillis( ) ) - time;
    
    Then, assuming time is a double, it gives the elapsed time in milliseconds.
  3. Alter the Sort class so that the constant CUTOFF is not final. We're going to vary it.
  4. Next change the main method of the Sort class so that it calls quicksort several times (let's say 20) for each value of the cutoff from 3 to 15, on a randomly permuted array of size 3000. Make sure you randomize the array before each call to quicksort! This is done by the method invocation Random.permute(a) (after all, it's not fair to sort an already sorted array). For each set of 20 runs of quicksort (at a given cutoff) compute the average run-time. Which cutoff gives the least run-time? The answer may surprise you (it's greater than 3).
  5. The Sort class is quite handy since it has all the sorting methods we've studied (recently, anyway): insertionsort, shellsort, heapsort, mergesort, and quicksort. So let's do some experiments with it.
  6. Repeat the same experiment you did for quicksort for each of those algorithms. Use the optimal cutoff for quicksort. Which algorithm wins the prize for least run-time?
  7. I could have asked you to compute comparisons rather than run-time to measure the complexity of quicksort. You would have found that a cutoff of 3 gives (roughly) the least number of comparisons, and that increasing the cutoff only increases the number of comparisons. Yet when it comes to the actual run-time, we need a cut-off of something more than 3. Why?
Hand in: Electronic submissions, with changes clearly indicated in the comments. Include reports of your results and your answers to the questions in the comments.
Last modified: 11/18/10 by Frederic Green.