/* StringSorter.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 Strings ** into ascending order using the classic Selection Sort algorithm. ** The ordering of strings (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 StringSorter { /* Rearranges the Strings in a[] so that they are in ascending ** order with respect to the ordering defined by the isLessThan() method. */ public void sort(String[] a) { sort(a, 0, a.length); } /* Rearranges the Strings in a[low..high) so that they are in ascending ** order with respect to the ordering defined by the isLessThan() method. /* pre: 0 <= low <= high <= a.length */ public void sort(String[] 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(String[] 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 s1 < s2. It is left to descendant classes to ** implement. */ protected abstract boolean isLessThan(String s1, String s2); /* pre: 0 <= i,j < b.length * post: references in b[i] and b[j] have been swapped */ private void swap(String[] b, int i, int j) { String temp = b[i]; b[i] = b[j]; b[j] = temp; } }