Class GenericSorting
- java.lang.Object
-
- cern.colt.GenericSorting
-
public class GenericSorting extends java.lang.Object
Generically sorts arbitrary shaped data (for example multiple arrays, 1,2 or 3-d matrices, and so on) using a quicksort or mergesort. This class addresses two problems, namely- Sorting multiple arrays in sync
- Sorting by multiple sorting criteria (primary, secondary, tertiary, ...)
Sorting multiple arrays in sync
Assume we have three arrays X, Y and Z. We want to sort all three arrays by X (or some arbitrary comparison function). For example, we have
X=[3, 2, 1], Y=[3.0, 2.0, 1.0], Z=[6.0, 7.0, 8.0]. The output should be
X=[1, 2, 3], Y=[1.0, 2.0, 3.0], Z=[8.0, 7.0, 6.0].How can we achive this? Here are several alternatives. We could ...
- make a list of Point3D objects, sort the list as desired using a comparison function, then copy the results back into X, Y and Z. The classic object-oriented way.
- make an index list [0,1,2,...,N-1], sort the index list using a comparison function, then reorder the elements of X,Y,Z as defined by the index list. Reordering cannot be done in-place, so we need to copy X to some temporary array, then copy in the right order back from the temporary into X. Same for Y and Z.
- use a generic quicksort or mergesort which, whenever two elements in X are swapped, also swaps the corresponding elements in Y and Z.
This class implements alternative 3. It operates on arbitrary shaped data. In fact, it has no idea what kind of data it is sorting. Comparisons and swapping are delegated to user provided objects which know their data and can do the job.
Lets call the generic data g (it may be one array, three linked lists or whatever). This class takes a user comparison function operating on two indexes (a,b), namely an
IntComparator
. The comparison function determines whether g[a] is equal, less or greater than g[b]. The sort, depending on its implementation, can decide to swap the data at index a with the data at index b. It calls a user providedSwapper
object that knows how to swap the data of these indexes.The following snippet shows how to solve the problem.
final int[] x; final double[] y; final double[] z; x = new int[] {3, 2, 1 }; y = new double[] {3.0, 2.0, 1.0}; z = new double[] {6.0, 7.0, 8.0}; // this one knows how to swap two indexes (a,b) Swapper swapper = new Swapper() { public void swap(int a, int b) { int t1; double t2, t3; t1 = x[a]; x[a] = x[b]; x[b] = t1; t2 = y[a]; y[a] = y[b]; y[b] = t2; t3 = z[a]; z[a] = z[b]; z[b] = t3; } }; // simple comparison: compare by X and ignore Y,Z
IntComparator comp = new IntComparator() { public int compare(int a, int b) { return x[a]==x[b] ? 0 : (x[a]<x[b] ? -1 : 1); } }; System.out.println("before:"); System.out.println("X="+Arrays.toString(x)); System.out.println("Y="+Arrays.toString(y)); System.out.println("Z="+Arrays.toString(z)); GenericSorting.quickSort(0, X.length, comp, swapper); // GenericSorting.mergeSort(0, X.length, comp, swapper); System.out.println("after:"); System.out.println("X="+Arrays.toString(x)); System.out.println("Y="+Arrays.toString(y)); System.out.println("Z="+Arrays.toString(z));Sorting by multiple sorting criterias (primary, secondary, tertiary, ...)
Assume again we have three arrays X, Y and Z. Now we want to sort all three arrays, primarily by Y, secondarily by Z (if Y elements are equal). For example, we have
X=[6, 7, 8, 9], Y=[3.0, 2.0, 1.0, 3.0], Z=[5.0, 4.0, 4.0, 1.0]. The output should be
X=[8, 7, 9, 6], Y=[1.0, 2.0, 3.0, 3.0], Z=[4.0, 4.0, 1.0, 5.0].Here is how to solve the problem. All code in the above example stays the same, except that we modify the comparison function as follows
//compare by Y, if that doesn't help, reside to Z IntComparator comp = new IntComparator() { public int compare(int a, int b) { if (y[a]==y[b]) return z[a]==z[b] ? 0 : (z[a]<z[b] ? -1 : 1); return y[a]<y[b] ? -1 : 1; } };
Notes
Sorts involving floating point data and not involving comparators, like, for example provided in the JDK
Arrays
and in the ColtSorting
handle floating point numbers in special ways to guarantee that NaN's are swapped to the end and -0.0 comes before 0.0. Methods delegating to comparators cannot do this. They rely on the comparator. Thus, if such boundary cases are an issue for the application at hand, comparators explicitly need to implement -0.0 and NaN aware comparisons. Remember: -0.0 < 0.0 == false, (-0.0 == 0.0) == true, as well as 5.0 < Double.NaN == false, 5.0 > Double.NaN == false. Same for float.Implementation
The quicksort is a derivative of the JDK 1.2 V1.26 algorithms (which are, in turn, based on Bentley's and McIlroy's fine work). The mergesort is a derivative of the JAL algorithms, with optimisations taken from the JDK algorithms. Both quick and merge sort are "in-place", i.e. do not allocate temporary memory (helper arrays). Mergesort is stable (by definition), while quicksort is not. A stable sort is, for example, helpful, if matrices are sorted successively by multiple columns. It preserves the relative position of equal elements.
-
-
Constructor Summary
Constructors Modifier Constructor Description protected
GenericSorting()
Makes this class non instantiable, but still let's others inherit from it.
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description private static void
inplace_merge(int first, int middle, int last, IntComparator comp, Swapper swapper)
Transforms two consecutive sorted ranges into a single sorted range.private static int
lower_bound(int first, int last, int x, IntComparator comp)
Performs a binary search on an already-sorted range: finds the first position where an element can be inserted without violating the ordering.private static int
med3(int a, int b, int c, IntComparator comp)
Returns the index of the median of the three indexed chars.static void
mergeSort(int fromIndex, int toIndex, IntComparator c, Swapper swapper)
Sorts the specified range of elements according to the order induced by the specified comparator.static void
quickSort(int fromIndex, int toIndex, IntComparator c, Swapper swapper)
Sorts the specified range of elements according to the order induced by the specified comparator.private static void
quickSort1(int off, int len, IntComparator comp, Swapper swapper)
Sorts the specified sub-array into ascending order.private static void
reverse(int first, int last, Swapper swapper)
Reverses a sequence of elements.private static void
rotate(int first, int middle, int last, Swapper swapper)
Rotate a range in place:array[middle]
is put inarray[first]
,array[middle+1]
is put inarray[first+1]
, etc.private static int
upper_bound(int first, int last, int x, IntComparator comp)
Performs a binary search on an already-sorted range: finds the last position where an element can be inserted without violating the ordering.private static void
vecswap(Swapper swapper, int a, int b, int n)
Swaps x[a ..
-
-
-
Field Detail
-
SMALL
private static final int SMALL
- See Also:
- Constant Field Values
-
MEDIUM
private static final int MEDIUM
- See Also:
- Constant Field Values
-
-
Method Detail
-
inplace_merge
private static void inplace_merge(int first, int middle, int last, IntComparator comp, Swapper swapper)
Transforms two consecutive sorted ranges into a single sorted range. The initial ranges are[first, middle)
and[middle, last)
, and the resulting range is[first, last)
. Elements in the first input range will precede equal elements in the second.
-
lower_bound
private static int lower_bound(int first, int last, int x, IntComparator comp)
Performs a binary search on an already-sorted range: finds the first position where an element can be inserted without violating the ordering. Sorting is by a user-supplied comparison function.- Parameters:
array
- Array containing the range.first
- Beginning of the range.last
- One past the end of the range.x
- Element to be searched for.comp
- Comparison function.- Returns:
- The largest index i such that, for every j in the
range
[first, i)
,comp.apply(array[j], x)
istrue
. - See Also:
Sorting.upper_bound(int[], int, int, int)
,Sorting#equal_range
,Sorting#binary_search
-
med3
private static int med3(int a, int b, int c, IntComparator comp)
Returns the index of the median of the three indexed chars.
-
mergeSort
public static void mergeSort(int fromIndex, int toIndex, IntComparator c, Swapper swapper)
Sorts the specified range of elements according to the order induced by the specified comparator. All elements in the range must be mutually comparable by the specified comparator (that is, c.compare(a, b) must not throw an exception for any indexes a and b in the range).This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance, and can approach linear performance on nearly sorted lists.
- Parameters:
fromIndex
- the index of the first element (inclusive) to be sorted.toIndex
- the index of the last element (exclusive) to be sorted.c
- the comparator to determine the order of the generic data.swapper
- an object that knows how to swap the elements at any two indexes (a,b).- See Also:
IntComparator
,Swapper
-
quickSort
public static void quickSort(int fromIndex, int toIndex, IntComparator c, Swapper swapper)
Sorts the specified range of elements according to the order induced by the specified comparator. All elements in the range must be mutually comparable by the specified comparator (that is, c.compare(a, b) must not throw an exception for any indexes a and b in the range).The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance.
- Parameters:
fromIndex
- the index of the first element (inclusive) to be sorted.toIndex
- the index of the last element (exclusive) to be sorted.c
- the comparator to determine the order of the generic data.swapper
- an object that knows how to swap the elements at any two indexes (a,b).- See Also:
IntComparator
,Swapper
-
quickSort1
private static void quickSort1(int off, int len, IntComparator comp, Swapper swapper)
Sorts the specified sub-array into ascending order.
-
reverse
private static void reverse(int first, int last, Swapper swapper)
Reverses a sequence of elements.- Parameters:
array
- Array containing the sequencefirst
- Beginning of the rangelast
- One past the end of the range- Throws:
java.lang.ArrayIndexOutOfBoundsException
- If the range is invalid.
-
rotate
private static void rotate(int first, int middle, int last, Swapper swapper)
Rotate a range in place:array[middle]
is put inarray[first]
,array[middle+1]
is put inarray[first+1]
, etc. Generally, the element in positioni
is put into position(i + (last-middle)) % (last-first)
.- Parameters:
array
- Array containing the rangefirst
- Beginning of the rangemiddle
- Index of the element that will be put inarray[first]
last
- One past the end of the range
-
upper_bound
private static int upper_bound(int first, int last, int x, IntComparator comp)
Performs a binary search on an already-sorted range: finds the last position where an element can be inserted without violating the ordering. Sorting is by a user-supplied comparison function.- Parameters:
array
- Array containing the range.first
- Beginning of the range.last
- One past the end of the range.x
- Element to be searched for.comp
- Comparison function.- Returns:
- The largest index i such that, for every j in the
range
[first, i)
,comp.apply(x, array[j])
isfalse
. - See Also:
Sorting.lower_bound(int[], int, int, int)
,Sorting#equal_range
,Sorting#binary_search
-
vecswap
private static void vecswap(Swapper swapper, int a, int b, int n)
Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)].
-
-