3.1. Abstraction
The abstract class for all sorting algorithms.
Abstract Sort
Let us create an abstract class AbstractSort:
public abstract class AbstractSort<T extends Comparable<T>> {
private final Comparator<T> comparator;
protected long comparisons;
protected long assignments;
/** @param comparator specifies the precedence of comparable keys. */
public AbstractSort(Comparator<T> comparator) {
this.comparator = comparator;
resetCounts();
}
/** @return the total number of comparisons performed during sort. */
public long getComparisonCount() {
return comparisons;
}
/** @return the total number of assignments performed during sort. */
public long getAssignmentCount() {
return assignments;
}
public void resetCounts() {
comparisons = assignments = 0;
}
}L2-4: member fields:comparator: specifies the precedence of comparable keys.comparisons: counts the number of comparisons performed during sorting.assignments: counts the number of assignments performed during sorting.
Let us define three helper methods, compareTo(), assign(), and swap():
L7: compares two keys in the array and increments the count.L18: assigns the value to the specific position in the array and increments the count.L29: swaps the values of the specific positions in the array by calling theassign()method.
These helper methods allow us to analyze the exact counts of those operations performed by different sorting algorithms.
How is it different to benchmark runtime speeds from counting these two operations?
Finally, let us define the default sort() that calls an overwritten abstract method, sort():
L5: calls the abstract methodsort()that overwrites it.L15: sorts thearrayin the range of (beginIndex,endIndex) as specified incomparator.
When would it be useful to sort a specific range in the input array?
Last updated
Was this helpful?