// default mechanism works
return (SortMetrics) super.clone();
} catch (CloneNotSupportedException e) {
// can't happen: this and Object both clone
throw new InternalError(e.toString());
}
}
}
The following class extends SortDouble. The SimpleSortDouble class implements doSort with a
very slow but simple sort algorithm (a "selection sort") whose primary advantage is that it is easy to code and
easy to understand:
class SimpleSortDouble extends SortDouble {
protected void doSort() {
for (int i = 0; i < getDataLength(); i++) {
for (int j = i + 1; j < getDataLength(); j++) {
if (compare(i, j) > 0)
swap(i, j);
}
}
}
}
Now we can write a test harness for sort algorithms that must be changed only slightly to test a new sort
algorithm. Here it is shown as a driver for testing the class SimpleSortDouble:
public class TestSort {
static double[] testData = {
0.3, 1.3e-2, 7.9, 3.17
};
public static void main(String[] args) {
SortDouble bsort = new SimpleSortDouble();
SortMetrics metrics = bsort.sort(testData);
System.out.println("Metrics: " + metrics);
for (int i = 0; i < testData.length; i++)
System.out.println("\t" + testData[i]);
}
}
The main method shows how code that drives a test works: It creates an object of a class extended from
SortDouble, provides it with the data to be sorted, and invokes sort. The sort method stores the data,
initializes the metrics, and then invokes the abstract method doSort. Each extended class implements
doSort to do its sorting, invoking getdataLength, compare, and swap when it needs to. When
doSort returns, the counts reflect the number of each operation performed. To test a different algorithm, you
can simply change the class name after the new. Here is what one run of TestSort looks like:
Metrics: 0 probes 6 compares 2 swaps
0.013
0.3
3.17
7.9