/* Sorter.java ** An instance of a child of this abstract class inherits methods from ** this class by which to sort an array (or a segment thereof) of any ** reference type into ascending order using the classic Selection Sort ** algorithm. The ordering of elements (which is determined by the ** criteria used in comparing them) is defined by the isLessThan() method, ** which here is abstract (and hence is left to be implemented by each ** child class). */ public abstract class Sorter { /* Rearranges the elements in a[] so that they are in ascending ** lexicographic order. */ public void sort(T[] a) { sort(a, 0, a.length); } /* pre: 0 <= low <= high <= a.length ** post: The elements in a[low..high) have been permuted so that ** they are in ascending order. */ public void sort(T[] a, int low, int high) { for (int i = low; i != high; i=i+1) { int locOfMin = locationOfMin(a, i, high); swap(a,i,locOfMin); } } /* pre: 0 <= low < high <= b.length ** post: value returned identifies a location within the array ** segment b[low..high) containing the minimum element ** in that segment. */ private int locationOfMin(T[] b, int low, int high) { int locOfMinSoFar = low; for (int j = low+1; j != high; j = j+1) { if (isLessThan(b[j], b[locOfMinSoFar])) { locOfMinSoFar = j; } } return locOfMinSoFar; } /* Returns true iff x < y. It is left to descendant classes to ** implement. */ protected abstract boolean isLessThan(T x, T y); /* pre: 0 <= i,j < b.length * post: references in b[i] and b[j] have been swapped */ private void swap(T[] b, int i, int j) { T temp = b[i]; b[i] = b[j]; b[j] = temp; } }