Debian Codegraph @

net/sf/saxon/expr/sort/GenericSorter.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.expr.sort;
9
10 /*
11 Copyright ? 1999 CERN - European Organization for Nuclear Research.
12 Permission to use, copy, moNumbererdify, distribute and sell this software and its documentation for any purpose
13 is hereby granted without fee, provided that the above copyright notice appear in all copies and
14 that both that copyright notice and this permission notice appear in supporting documentation.
15 CERN makes no representations about the suitability of this software for any purpose.
16 It is provided "as is" without expressed or implied warranty.
17 */
18
19 /**
20 * Modified by Michael Kay to use the Saxon Sortable interface rather than a separate IntComparator and Swapper
21 */
22
23
24 /**
25 * Generically sorts arbitrary shaped data (for example multiple arrays, 1,2 or 3-d matrices, and so on) using a
26 * quicksort or mergesort. This class addresses two problems, namely
27 * <ul>
28 * <li><i>Sorting multiple arrays in sync</i></li>
29 * <li><i>Sorting by multiple sorting criteria</i> (primary, secondary, tertiary,
30 * ...)</li>
31 * </ul>
32 * <h4>Sorting multiple arrays in sync</h4>
33 * <p>Assume we have three arrays X, Y and Z. We want to sort all three arrays by
34 * X (or some arbitrary comparison function). For example, we have
35 * <tt>X=[3, 2, 1], Y=[3.0, 2.0, 1.0], Z=[6.0, 7.0, 8.0]</tt>. The output should
36 * be <tt>X=[1, 2, 3], Y=[1.0, 2.0, 3.0], Z=[8.0, 7.0, 6.0]</tt>. </p>
37 * <p>How can we achieve this? Here are several alternatives. We could ... </p>
38 * <ol>
39 * <li>make a list of Point3D objects, sort the list as desired using a comparison
40 * function, then copy the results back into X, Y and Z. The classic object-oriented
41 * way. </li>
42 * <li>make an index list [0,1,2,...,N-1], sort the index list using a comparison function,
43 * then reorder the elements of X,Y,Z as defined by the index list. Reordering
44 * cannot be done in-place, so we need to copy X to some temporary array, then
45 * copy in the right order back from the temporary into X. Same for Y and Z. </li>
46 * <li>use a generic quicksort or mergesort which, whenever two elements in X are swapped,
47 * also swaps the corresponding elements in Y and Z. </li>
48 * </ol>
49 * <p>Alternatives 1 and 2 involve quite a lot of copying and allocate significant amounts
50 * of temporary memory. Alternative 3 involves more swapping, more polymorphic message dispatches,
51 * no copying and does not need any temporary memory.</p>
52 * <p>This class implements alternative 3. It operates on arbitrary shaped data.
53 * In fact, it has no idea what kind of data it is sorting. Comparisons and swapping
54 * are delegated to user provided objects which know their data and can do the
55 * job.</p>
56 * <p>Lets call the generic data <tt>g</tt> (it may be one array, three linked lists
57 * or whatever). This class takes a user comparison function operating on two indexes
58 * <tt>(a,b)</tt>, namely an {@link Sortable}. The comparison function determines
59 * whether <tt>g[a]</tt> is equal, less or greater than <tt>g[b]</tt>. The sort,
60 * depending on its implementation, can decide to swap the data at index <tt>a</tt>
61 * with the data at index <tt>b</tt>. It calls a user provided {@link Sortable}
62 * object that knows how to swap the data of these indexes.</p>
63 * <p>The following snippet shows how to solve the problem.</p>
64 * <pre>
65 * final int[] x;
66 * final double[] y;
67 * final double[] z;
68 *
69 * x = new int[] {3, 2, 1 };
70 * y = new double[] {3.0, 2.0, 1.0};
71 * z = new double[] {6.0, 7.0, 8.0};
72 *
73 *
74 * // this one knows how to swap two indexes (a,b)
75 * Swapper swapper = new Swapper() {
76 * &nbsp;&nbsp;&nbsp;public void swap(int a, int b) {
77 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;int t1; double t2, t3;
78 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t1 = x[a]; x[a] = x[b]; x[b] = t1;
79 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t2 = y[a]; y[a] = y[b]; y[b] = t2;
80 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;t3 = z[a]; z[a] = z[b]; z[b] = t3;
81 * &nbsp;&nbsp;&nbsp;}
82 * };
83 * // simple comparison: compare by X and ignore Y,Z
84 * IntComparator comp = new IntComparator() {
85 * &nbsp;&nbsp;&nbsp;public int compare(int a, int b) {
86 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return x[a]==x[b] ? 0 : (x[a]&lt;x[b] ? -1 : 1);
87 * &nbsp;&nbsp;&nbsp;}
88 * };
89 *
90 * System.out.println("before:");
91 * System.out.println("X="+Arrays.toString(x));
92 * System.out.println("Y="+Arrays.toString(y));
93 * System.out.println("Z="+Arrays.toString(z));
94 *
95 * GenericSorting.quickSort(0, X.length, comp, swapper);
96 * // GenericSorting.mergeSort(0, X.length, comp, swapper);
97 *
98 * System.out.println("after:");
99 * System.out.println("X="+Arrays.toString(x));
100 * System.out.println("Y="+Arrays.toString(y));
101 * System.out.println("Z="+Arrays.toString(z));
102 * </pre>
103 * <h4>Sorting by multiple sorting criterias (primary, secondary, tertiary, ...)</h4>
104 * <p>Assume again we have three arrays X, Y and Z. Now we want to sort all three
105 * arrays, primarily by Y, secondarily by Z (if Y elements are equal). For example,
106 * we have
107 * <tt>X=[6, 7, 8, 9], Y=[3.0, 2.0, 1.0, 3.0], Z=[5.0, 4.0, 4.0, 1.0]</tt>. The
108 * output should be <tt>
109 * X=[8, 7, 9, 6], Y=[1.0, 2.0, 3.0, 3.0], Z=[4.0, 4.0, 1.0, 5.0]</tt>. </p>
110 * <p>Here is how to solve the problem. All code in the above example stays the same,
111 * except that we modify the comparison function as follows</p>
112 * <pre>
113 * //compare by Y, if that doesn't help, reside to Z
114 * IntComparator comp = new IntComparator() {
115 * &nbsp;&nbsp;&nbsp;public int compare(int a, int b) {
116 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if (y[a]==y[b]) return z[a]==z[b] ? 0 : (z[a]&lt;z[b] ? -1 : 1);
117 * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return y[a]&lt;y[b] ? -1 : 1;
118 * &nbsp;&nbsp;&nbsp;}
119 * };
120 * </pre>
121 * <h4>Notes</h4>
122 * <p>Sorts involving floating point data and not involving comparators, like, for
123 * example provided in the JDK {@link java.util.Arrays} and in the Colt
124 * (cern.colt.Sorting) handle floating point numbers in special ways to guarantee
125 * that NaN's are swapped to the end and -0.0 comes before 0.0. Methods delegating
126 * to comparators cannot do this. They rely on the comparator. Thus, if such boundary
127 * cases are an issue for the application at hand, comparators explicitly need
128 * to implement -0.0 and NaN aware comparisons. Remember: <tt>-0.0 &lt; 0.0 == false</tt>,
129 * <tt>(-0.0 == 0.0) == true</tt>, as well as <tt>5.0 &lt; Double.NaN == false</tt>,
130 * <tt>5.0 &gt; Double.NaN == false</tt>. Same for <tt>float</tt>.
131 * <h4>Implementation</h4>
132 * <p>The quicksort is a derivative of the JDK 1.2 V1.26 algorithms (which are, in
133 * turn, based on Bentley's and McIlroy's fine work).
134 * The mergesort is a derivative of the JAL algorithms, with optimisations taken from the JDK algorithms.
135 * Both quick and merge sort are "in-place", i.e. do not allocate temporary memory (helper arrays).
136 * Mergesort is <i>stable</i> (by definition), while quicksort is not.
137 * A stable sort is, for example, helpful, if matrices are sorted successively
138 * by multiple columns. It preserves the relative position of equal elements.</p>
139 *
140 * @author [email protected]
141 * @version 1.0, 03-Jul-99
142 */
143 public class GenericSorter extends Object {
144
145 private static final int SMALL = 7;
146 private static final int MEDIUM = 7;
147 private static final int LARGE = 40;
148
149
150 /**
151 * Makes this class non instantiable, but still let's others inherit from it.
152 */
153 protected GenericSorter() {
154 }
155
156 /**
157 * Sorts the specified range of elements according
158 * to the order induced by the specified comparator. All elements in the
159 * range must be <i>mutually comparable</i> by the specified comparator
160 * (that is, <tt>c.compare(a, b)</tt> must not throw an
161 * exception for any indexes <tt>a</tt> and
162 * <tt>b</tt> in the range).
163 * <p>The sorting algorithm is a tuned quicksort,
164 * adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a
165 * Sort Function", Software-Practice and Experience, Vol. 23(11)
166 * P. 1249-1265 (November 1993). For details, see
167 * http://citeseer.ist.psu.edu/bentley93engineering.html.
168 * This algorithm offers n*log(n) performance on many data sets that cause other
169 * quicksorts to degrade to quadratic performance.</p>
170 *
171 * @param fromIndex the index of the first element (inclusive) to be sorted.
172 * @param toIndex the index of the last element (exclusive) to be sorted.
173 * @param c the comparator to determine the order of the generic data;
174 * an object that knows how to swap the elements at any two indexes (a,b).
175 */
176 public static void quickSort(int fromIndex, int toIndex, /*@NotNull*/ Sortable c) {
177 quickSort1(fromIndex, toIndex - fromIndex, c);
178 }
179
180 /**
181 * Sorts the specified sub-array into ascending order.
182 */
183 private static void quickSort1(int off, int len, Sortable comp) {
184 // Insertion sort on smallest arrays
185 if (len < SMALL) {
186 for (int i = off; i < len + off; i++)
187 for (int j = i; j > off && (comp.compare(j - 1, j) > 0); j--) {
188 comp.swap(j, j - 1);
189 }
190 return;
191 }
192
193 // Choose a partition element, v
194 int m = off + (len >>> 1); // len/2; // Small arrays, middle element
195
196 if (len > MEDIUM) {
197 int l = off;
198 int n = off + len - 1;
199 if (len > LARGE) { // Big arrays, pseudomedian of 9
200 int s = len >>> 3; // len/8;
201 l = med3(l, l + s, l + 2 * s, comp);
202 m = med3(m - s, m, m + s, comp);
203 n = med3(n - 2 * s, n - s, n, comp);
204 }
205 // m = med3(l, m, n, comp); // Mid-size, med of 3
206 // manually inlined (most time is spent near the leafs of the recursion tree)
207 //a = comp.compare(l,m);
208 //b = comp.compare(l,n);
209 int c = comp.compare(m, n);
210 m = (comp.compare(l, m) < 0 ?
211 (c < 0 ? m : comp.compare(l, n) < 0 ? n : l) :
212 (c > 0 ? m : comp.compare(l, n) > 0 ? n : l));
213 }
214 //long v = x[m];
215
216 // Establish Invariant: v* (<v)* (>v)* v*
217 int a = off, b = a, c = off + len - 1, d = c;
218 while (true) {
219 int comparison;
220 while (b <= c && ((comparison = comp.compare(b, m)) <= 0)) {
221 if (comparison == 0) {
222 if (a == m) m = b; // pivot is moving target; DELTA to JDK !!!
223 else if (b == m) m = a; // pivot is moving target; DELTA to JDK !!!
224 comp.swap(a++, b);
225 }
226 b++;
227 }
228 while (c >= b && ((comparison = comp.compare(c, m)) >= 0)) {
229 if (comparison == 0) {
230 if (c == m) m = d; // pivot is moving target; DELTA to JDK !!!
231 else if (d == m) m = c; // pivot is moving target; DELTA to JDK !!!
232 comp.swap(c, d--);
233 }
234 c--;
235 }
236 if (b > c) break;
237 if (b == m) m = d; // pivot is moving target; DELTA to JDK !!!
238 else if (c == m) m = c; // pivot is moving target; DELTA to JDK !!!
239 comp.swap(b++, c--);
240 }
241
242 // Swap partition elements back to middle
243
244 int s = Math.min(a - off, b - a);
245 // vecswap(swapper, off, b-s, s);
246 // manually inlined
247 int aa = off;
248 int bb = b - s;
249 while (--s >= 0) comp.swap(aa++, bb++);
250 int n = off + len;
251 s = Math.min(d - c, n - d - 1);
252 // vecswap(swapper, b, n-s, s); // manually inlined
253 aa = b;
254 bb = n - s;
255 while (--s >= 0) comp.swap(aa++, bb++);
256
257 // Recursively sort non-partition-elements
258 if ((s = b - a) > 1)
259 quickSort1(off, s, comp);
260 if ((s = d - c) > 1)
261 quickSort1(n - s, s, comp);
262 }
263
264 /**
265 * Returns the index of the median of the three indexed elements.
266 */
267 private static int med3(int a, int b, int c, Sortable comp) {
268 int bc = comp.compare(b, c);
269 return (comp.compare(a, b) < 0 ?
270 (bc < 0 ? b : comp.compare(a, c) < 0 ? c : a) :
271 (bc > 0 ? b : comp.compare(a, c) > 0 ? c : a));
272 }
273
274
275 // /**
276 // * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)].
277 // */
278 // private static void vecswap(Swapper swapper, int a, int b, int n) {
279 // for (int i=0; i<n; i++, a++, b++) swapper.swap(a, b);
280 // }
281
282 /**
283 * Sorts the specified range of elements according
284 * to the order induced by the specified comparator. All elements in the
285 * range must be <i>mutually comparable</i> by the specified comparator
286 * (that is, <tt>c.compare(a, b)</tt> must not throw an
287 * exception for any indexes <tt>a</tt> and
288 * <tt>b</tt> in the range).
289 * <p>This sort is guaranteed to be <i>stable</i>: equal elements will
290 * not be reordered as a result of the sort.</p>
291 * <p>The sorting algorithm is a modified mergesort (in which the merge is
292 * omitted if the highest element in the low sublist is less than the
293 * lowest element in the high sublist). This algorithm offers guaranteed
294 * n*log(n) performance, and can approach linear performance on nearly
295 * sorted lists.</p>
296 *
297 * @param fromIndex the index of the first element (inclusive) to be sorted.
298 * @param toIndex the index of the last element (exclusive) to be sorted.
299 * @param c the comparator to determine the order of the generic data;
300 * an object that knows how to swap the elements at any two indexes (a,b).
301 */
302 public static void mergeSort(int fromIndex, int toIndex, Sortable c) {
303 /*
304 * We retain the same method signature as quickSort. Given only a
305 * comparator and swapper we do not know how to copy and move elements
306 * from/to temporary arrays. Hence, in contrast to the JDK mergesorts
307 * this is an "in-place" mergesort, i.e. does not allocate any temporary
308 * arrays. A non-inplace mergesort would be faster in most cases, but
309 * would require non-intuitive delegate objects. Remember that an
310 * in-place merge phase requires N logN swaps, while an out-of-place
311 * merge phase requires only N swaps. This doesn't matter much if swaps
312 * are cheap and comparisons are expensive. Nonetheless this can
313 * certainly be suboptimal.
314 */
315
316
317 // Insertion sort on smallest arrays
318 if (toIndex - fromIndex < SMALL) {
319 for (int i = fromIndex; i < toIndex; i++) {
320 for (int j = i; j > fromIndex && (c.compare(j - 1, j) > 0); j--) {
321 c.swap(j, j - 1);
322 }
323 }
324 return;
325 }
326
327 // Recursively sort halves
328 int mid = (fromIndex + toIndex) >>> 1; // (fromIndex + toIndex) / 2;
329 mergeSort(fromIndex, mid, c);
330 mergeSort(mid, toIndex, c);
331
332 // If list is already sorted, nothing left to do. This is an
333 // optimization that results in faster sorts for nearly ordered lists.
334 if (c.compare(mid - 1, mid) <= 0) return;
335
336 // Merge sorted halves
337 inplaceMerge(fromIndex, mid, toIndex, c);
338 }
339
340 /**
341 * Transforms two consecutive sorted ranges into a single sorted
342 * range. The initial ranges are <code>[first, middle)</code>
343 * and <code>[middle, last)</code>, and the resulting range is
344 * <code>[first, last)</code>.
345 * Elements in the first input range will precede equal elements in the
346 * second.
347 */
348 private static void inplaceMerge(int first, int middle, int last, Sortable comp) {
349 if (first >= middle || middle >= last)
350 return;
351 if (last - first == 2) {
352 if (comp.compare(middle, first) < 0) {
353 comp.swap(first, middle);
354 }
355 return;
356 }
357 int firstCut;
358 int secondCut;
359 if (middle - first > last - middle) {
360 firstCut = first + ((middle - first) >>> 1); // first + ((middle - first) / 2);
361 // secondCut = lower_bound(middle, last, firstCut, comp);
362 // manually inlined for speed (speedup = 2)
363 int _first = middle;
364 int len = last - _first;
365 while (len > 0) {
366 int half = len >>> 1; // len / 2;
367 int mid = _first + half;
368 if (comp.compare(mid, firstCut) < 0) {
369 _first = mid + 1;
370 len -= half + 1;
371 } else {
372 len = half;
373 }
374 }
375 secondCut = _first;
376 } else {
377 secondCut = middle + ((last - middle) >>> 1); // middle + ((last - middle) / 2);
378 // firstCut = upper_bound(first, middle, secondCut, comp);
379 // manually inlined for speed (speedup = 2)
380 int _first = first;
381 int len = middle - _first;
382 while (len > 0) {
383 int half = len >>> 1; // len / 2;
384 int mid = _first + half;
385 if (comp.compare(secondCut, mid) < 0) {
386 len = half;
387 } else {
388 _first = mid + 1;
389 len -= half + 1;
390 }
391 }
392 firstCut = _first;
393 }
394
395 // rotate(firstCut, middle, secondCut, swapper);
396 // is manually inlined for speed
397 // (hotspot compiler inlining in recursive methods seems to work only for
398 // small call depths, even if methods are "static private")
399 // speedup = 1.7
400 // begin inline
401 int first2 = firstCut;
402 int middle2 = middle;
403 int last2 = secondCut;
404 if (middle2 != first2 && middle2 != last2) {
405 int first1 = first2;
406 int last1 = middle2;
407 while (first1 < --last1) comp.swap(first1++, last1);
408 first1 = middle2;
409 last1 = last2;
410 while (first1 < --last1) comp.swap(first1++, last1);
411 first1 = first2;
412 last1 = last2;
413 while (first1 < --last1) comp.swap(first1++, last1);
414 }
415 // end inline
416
417 middle = firstCut + (secondCut - middle);
418 inplaceMerge(first, firstCut, middle, comp);
419 inplaceMerge(middle, secondCut, last, comp);
420 }
421
422 // /**
423 // * Performs a binary search on an already-sorted range: finds the first
424 // * position where an element can be inserted without violating the ordering.
425 // * Sorting is by a user-supplied comparison function.
426 // * @param array Array containing the range.
427 // * @param first Beginning of the range.
428 // * @param last One past the end of the range.
429 // * @param x Element to be searched for.
430 // * @param comp Comparison function.
431 // * @return The largest index i such that, for every j in the
432 // * range <code>[first, i)</code>,
433 // * <code>comp.apply(array[j], x)</code> is
434 // * <code>true</code>.
435 // * @see Sorting#upper_bound
436 // * @see Sorting#equal_range
437 // * @see Sorting#binary_search
438 // */
439 // private static int lower_bound(int first, int last, int x, IntComparator comp) {
440 // int len = last - first;
441 // while (len > 0) {
442 // int half = len >>> 1; // len / 2;
443 // int middle = first + half;
444 // if (comp.compare(middle, x)<0) {
445 // first = middle + 1;
446 // len -= half + 1;
447 // }
448 // else {
449 // len = half;
450 // }
451 // }
452 // return first;
453 // }
454 //
455 // /**
456 // * Performs a binary search on an already-sorted range: finds the last
457 // * position where an element can be inserted without violating the ordering.
458 // * Sorting is by a user-supplied comparison function.
459 // * @param array Array containing the range.
460 // * @param first Beginning of the range.
461 // * @param last One past the end of the range.
462 // * @param x Element to be searched for.
463 // * @param comp Comparison function.
464 // * @return The largest index i such that, for every j in the
465 // * range <code>[first, i)</code>,
466 // * <code>comp.apply(x, array[j])</code> is
467 // * <code>false</code>.
468 // * @see Sorting#lower_bound
469 // * @see Sorting#equal_range
470 // * @see Sorting#binary_search
471 // */
472 // private static int upper_bound(int first, int last, int x, IntComparator comp) {
473 // int len = last - first;
474 // while (len > 0) {
475 // int half = len >>> 1; // len / 2;
476 // int middle = first + half;
477 // if (comp.compare(x, middle)<0) {
478 // len = half;
479 // }
480 // else {
481 // first = middle + 1;
482 // len -= half + 1;
483 // }
484 // }
485 // return first;
486 // }
487
488 }