Practical 7
Practical 7
The class Sorting.java contains just one method called selectionSort which takes an array of integer
values and is meant to sort it using the selection sort algorithm. Your first task is to implement this
method using the pseudo code given in lectures, then check that it works using the method
selectionSortTest that is provided in SortingTest.java. This test method introduces a new assertion
test that you may have not seen before called assertArrayEquals. This test takes an expected array
and compares its contents with an array that you have produced.
Once you have managed to get the selectionSort algorithm to work, your next task is to see how long
it takes to run for different sized data sets. A method called sortForSize has been provided for you in
SortingTest.java. This method will create an array of a given size ‘n’, call your selectionSort method
and note how long it took to run in nano-seconds. The test method timeSelectionSort has been
provided which will make a single call to sortForSize and print out the number of items sorted and
how long it took.
Add some additional calls to sortForSize with different sizes of data set and build up a list of items to
sort versus time taken. Use this data in Excel to plot the relationship between data set size and time
to sort and confirm the shape matches the N 2 computational order discussed in lectures.
Note: Do not try to sort more than 50,000 items – it will take increasingly longer to run and your
computer may slow down when large value of ‘n’ are used. To plot this data, use a scatter plot in
Excel (with connecting lines if you like). The value for ‘n’ should be on the ‘x’ axis and the time taken
should be on the ‘y’ axis’.
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/
Arrays.html#sort(java.lang.Object%5B%5D)
1 Incidentally, TimSort is only used for objects. For arrays of primitives like int and double, a variant of
QuickSort is used.
All you have to do is provide a way for Java to know whether one object in a class is more-than, less-
than or equal-to another. We do this by having the class implement the Comparable interface.
2. Depending on the IDE you’re using you might get a warning now that you need to implement the
compareTo() method. If this happens you can usually click on a button to generate a template for
this method, or you can type it yourself. The template looks like this:
[Checkpoint 7.1] Show your selection sort code and chart to a demonstrator. Then show the
demonstrator your compareTo() method, and run SortingExperiment to show that the accounts are
correctly sorted.