CS 161 Lab #7

October 29th

Goals:

This lab will give you a chance to work first-hand with the sorting code we developed in class, and to investigate its performance.

Directions:

  1. Download the SortingLab project and extract its contents, then start BlueJ and open the project.
  2. Take a moment to familiarize yourself with the Java code in the SortTest class. SortTest instances contain an array of integers, and provides methods for sorting and displaying these integers. You can generate new arrays of random values via the generateData method. The examples below illustrate interactions with a SortTest instance:

    > SortTest s = new SortTest();
    > s.toString()
    "[28, 35, 40, 49, 29, 17, 40, 28, 35, 13]"  (String)
    > s.selectionSort();
    > s.toString()
    "[13, 17, 28, 28, 29, 35, 35, 40, 40, 49]"  (String)
    > s.generateData(15);
    > s.toString()
    "[17, 30, 49, 20, 3, 71, 28, 54, 59, 27, 32, 24, 40, 15, 58]"  (String)
    > s.selectionSort();
    > s.toString()
    "[3, 15, 17, 20, 24, 27, 28, 30, 32, 40, 49, 54, 58, 59, 71]"  (String)
    
  3. In class, we calculated that it would take N×(N-1)/2 comparisons to sort an array of N items. It would be nice to test this experimentally. Add code to the selectionSort method so that it counts the number of comparisons performed during a sorting operation, and prints the results. (Your output should look like that below.) Do the results match our predictions? (You don't need to program in the actual formula — just compare some sample sorting results to what the formula predicts.) If you sort an already-sorted array, does it change the number of comparisons?

    > SortTest s = new SortTest();
    > s.generateData(100);
    > s.selectionSort();
    Required 4950 comparisons to sort 100 items.
    
  4. It's pretty easy to verify that selectionSort is producing correctly-sorted output for small collections of integers, but it would be nice to know that it works for much larger arrays as well. Finish the definition of ordered so that it returns true if the values in the numbers array are in increasing order, false otherwise. More precisely, it should return true if the values are not in decreasing order — arrays could contain duplicate values, so neighboring values in a sorted array could be identical. Use your new method to verify that the sorting is working correctly:

    > SortTest s = new SortTest();
    > s.toString()
    "[28, 35, 40, 49, 29, 17, 40, 28, 35, 13]"  (String)
    > s.ordered()
    false  (boolean)
    > s.selectionSort();
    > s.toString()
    "[13, 17, 28, 28, 29, 35, 35, 40, 40, 49]"  (String)
    > s.ordered()
    true  (boolean)
    > s.generateData(10000);
    > s.selectionSort();
    > s.ordered()
    true  (boolean)
    
If time permits, consider trying one of the following exercises:


Brad Richards, 2009