1 /* Arrays.java -- Utility class with methods to operate on arrays
2 Copyright (C) 1998, 1999 Free Software Foundation, Inc.
4 This file is part of GNU Classpath.
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2, or (at your option)
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; see the file COPYING. If not, write to the
18 Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 As a special exception, if you link this library with other files to
22 produce an executable, this library does not by itself cause the
23 resulting executable to be covered by the GNU General Public License.
24 This exception does not however invalidate any other reasons why the
25 executable file might be covered by the GNU General Public License. */
29 // ~ Fix the behaviour of sort and binarySearch as applied to float and double
30 // arrays containing NaN values. See the JDC, bug ID 4143272.
35 * This class contains various static utility methods performing operations on
36 * arrays, and a method to provide a List "view" of an array to facilitate
37 * using arrays with Collection-based APIs.
42 * This class is non-instantiable.
47 private static Comparator defaultComparator = new Comparator() {
48 public int compare(Object o1, Object o2) {
49 return ((Comparable)o1).compareTo(o2);
54 * Perform a binary search of a byte array for a key. The array must be
55 * sorted (as by the sort() method) - if it is not, the behaviour of this
56 * method is undefined, and may be an infinite loop. If the array contains
57 * the key more than once, any one of them may be found. Note: although the
58 * specification allows for an infinite loop if the array is unsorted, it
59 * will not happen in this implementation.
61 * @param a the array to search (must be sorted)
62 * @param key the value to search for
63 * @returns the index at which the key was found, or -n-1 if it was not
64 * found, where n is the index of the first value higher than key or
65 * a.length if there is no such value.
67 public static int binarySearch(byte[] a, byte key) {
69 int hi = a.length - 1;
72 mid = (low + hi) >> 1;
73 final byte d = a[mid];
79 low = ++mid; // This gets the insertion point right on the last loop
86 * Perform a binary search of a char array for a key. The array must be
87 * sorted (as by the sort() method) - if it is not, the behaviour of this
88 * method is undefined, and may be an infinite loop. If the array contains
89 * the key more than once, any one of them may be found. Note: although the
90 * specification allows for an infinite loop if the array is unsorted, it
91 * will not happen in this implementation.
93 * @param a the array to search (must be sorted)
94 * @param key the value to search for
95 * @returns the index at which the key was found, or -n-1 if it was not
96 * found, where n is the index of the first value higher than key or
97 * a.length if there is no such value.
99 public static int binarySearch(char[] a, char key) {
101 int hi = a.length - 1;
104 mid = (low + hi) >> 1;
105 final char d = a[mid];
108 } else if (d > key) {
111 low = ++mid; // This gets the insertion point right on the last loop
118 * Perform a binary search of a double array for a key. The array must be
119 * sorted (as by the sort() method) - if it is not, the behaviour of this
120 * method is undefined, and may be an infinite loop. If the array contains
121 * the key more than once, any one of them may be found. Note: although the
122 * specification allows for an infinite loop if the array is unsorted, it
123 * will not happen in this implementation.
125 * @param a the array to search (must be sorted)
126 * @param key the value to search for
127 * @returns the index at which the key was found, or -n-1 if it was not
128 * found, where n is the index of the first value higher than key or
129 * a.length if there is no such value.
131 public static int binarySearch(double[] a, double key) {
133 int hi = a.length - 1;
136 mid = (low + hi) >> 1;
137 final double d = a[mid];
140 } else if (d > key) {
143 low = ++mid; // This gets the insertion point right on the last loop
150 * Perform a binary search of a float array for a key. The array must be
151 * sorted (as by the sort() method) - if it is not, the behaviour of this
152 * method is undefined, and may be an infinite loop. If the array contains
153 * the key more than once, any one of them may be found. Note: although the
154 * specification allows for an infinite loop if the array is unsorted, it
155 * will not happen in this implementation.
157 * @param a the array to search (must be sorted)
158 * @param key the value to search for
159 * @returns the index at which the key was found, or -n-1 if it was not
160 * found, where n is the index of the first value higher than key or
161 * a.length if there is no such value.
163 public static int binarySearch(float[] a, float key) {
165 int hi = a.length - 1;
168 mid = (low + hi) >> 1;
169 final float d = a[mid];
172 } else if (d > key) {
175 low = ++mid; // This gets the insertion point right on the last loop
182 * Perform a binary search of an int array for a key. The array must be
183 * sorted (as by the sort() method) - if it is not, the behaviour of this
184 * method is undefined, and may be an infinite loop. If the array contains
185 * the key more than once, any one of them may be found. Note: although the
186 * specification allows for an infinite loop if the array is unsorted, it
187 * will not happen in this implementation.
189 * @param a the array to search (must be sorted)
190 * @param key the value to search for
191 * @returns the index at which the key was found, or -n-1 if it was not
192 * found, where n is the index of the first value higher than key or
193 * a.length if there is no such value.
195 public static int binarySearch(int[] a, int key) {
197 int hi = a.length - 1;
200 mid = (low + hi) >> 1;
201 final int d = a[mid];
204 } else if (d > key) {
207 low = ++mid; // This gets the insertion point right on the last loop
214 * Perform a binary search of a long array for a key. The array must be
215 * sorted (as by the sort() method) - if it is not, the behaviour of this
216 * method is undefined, and may be an infinite loop. If the array contains
217 * the key more than once, any one of them may be found. Note: although the
218 * specification allows for an infinite loop if the array is unsorted, it
219 * will not happen in this implementation.
221 * @param a the array to search (must be sorted)
222 * @param key the value to search for
223 * @returns the index at which the key was found, or -n-1 if it was not
224 * found, where n is the index of the first value higher than key or
225 * a.length if there is no such value.
227 public static int binarySearch(long[] a, long key) {
229 int hi = a.length - 1;
232 mid = (low + hi) >> 1;
233 final long d = a[mid];
236 } else if (d > key) {
239 low = ++mid; // This gets the insertion point right on the last loop
246 * Perform a binary search of a short array for a key. The array must be
247 * sorted (as by the sort() method) - if it is not, the behaviour of this
248 * method is undefined, and may be an infinite loop. If the array contains
249 * the key more than once, any one of them may be found. Note: although the
250 * specification allows for an infinite loop if the array is unsorted, it
251 * will not happen in this implementation.
253 * @param a the array to search (must be sorted)
254 * @param key the value to search for
255 * @returns the index at which the key was found, or -n-1 if it was not
256 * found, where n is the index of the first value higher than key or
257 * a.length if there is no such value.
259 public static int binarySearch(short[] a, short key) {
261 int hi = a.length - 1;
264 mid = (low + hi) >> 1;
265 final short d = a[mid];
268 } else if (d > key) {
271 low = ++mid; // This gets the insertion point right on the last loop
278 * This method does the work for the Object binary search methods.
279 * @exception NullPointerException if the specified comparator is null.
280 * @exception ClassCastException if the objects are not comparable by c.
282 private static int objectSearch(Object[] a, Object key, final Comparator c) {
284 int hi = a.length - 1;
287 mid = (low + hi) >> 1;
288 final int d = c.compare(key, a[mid]);
294 low = ++mid; // This gets the insertion point right on the last loop
301 * Perform a binary search of an Object array for a key, using the natural
302 * ordering of the elements. The array must be sorted (as by the sort()
303 * method) - if it is not, the behaviour of this method is undefined, and may
304 * be an infinite loop. Further, the key must be comparable with every item
305 * in the array. If the array contains the key more than once, any one of
306 * them may be found. Note: although the specification allows for an infinite
307 * loop if the array is unsorted, it will not happen in this (JCL)
310 * @param a the array to search (must be sorted)
311 * @param key the value to search for
312 * @returns the index at which the key was found, or -n-1 if it was not
313 * found, where n is the index of the first value higher than key or
314 * a.length if there is no such value.
315 * @exception ClassCastException if key could not be compared with one of the
317 * @exception NullPointerException if a null element has compareTo called
319 public static int binarySearch(Object[] a, Object key) {
320 return objectSearch(a, key, defaultComparator);
324 * Perform a binary search of an Object array for a key, using a supplied
325 * Comparator. The array must be sorted (as by the sort() method with the
326 * same Comparator) - if it is not, the behaviour of this method is
327 * undefined, and may be an infinite loop. Further, the key must be
328 * comparable with every item in the array. If the array contains the key
329 * more than once, any one of them may be found. Note: although the
330 * specification allows for an infinite loop if the array is unsorted, it
331 * will not happen in this (JCL) implementation.
333 * @param a the array to search (must be sorted)
334 * @param key the value to search for
335 * @param c the comparator by which the array is sorted
336 * @returns the index at which the key was found, or -n-1 if it was not
337 * found, where n is the index of the first value higher than key or
338 * a.length if there is no such value.
339 * @exception ClassCastException if key could not be compared with one of the
342 public static int binarySearch(Object[] a, Object key, Comparator c) {
343 return objectSearch(a, key, c);
347 * Compare two byte arrays for equality.
349 * @param a1 the first array to compare
350 * @param a2 the second array to compare
351 * @returns true if a1 and a2 are both null, or if a2 is of the same length
352 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
354 public static boolean equals(byte[] a1, byte[] a2) {
356 // Quick test which saves comparing elements of the same array, and also
357 // catches the case that both are null.
363 // If they're the same length, test each element
364 if (a1.length == a2.length) {
365 for (int i = 0; i < a1.length; i++) {
366 if (a1[i] != a2[i]) {
373 // If a1 == null or a2 == null but not both then we will get a NullPointer
374 } catch (NullPointerException e) {
381 * Compare two char arrays for equality.
383 * @param a1 the first array to compare
384 * @param a2 the second array to compare
385 * @returns true if a1 and a2 are both null, or if a2 is of the same length
386 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
388 public static boolean equals(char[] a1, char[] a2) {
390 // Quick test which saves comparing elements of the same array, and also
391 // catches the case that both are null.
397 // If they're the same length, test each element
398 if (a1.length == a2.length) {
399 for (int i = 0; i < a1.length; i++) {
400 if (a1[i] != a2[i]) {
407 // If a1 == null or a2 == null but not both then we will get a NullPointer
408 } catch (NullPointerException e) {
415 * Compare two double arrays for equality.
417 * @param a1 the first array to compare
418 * @param a2 the second array to compare
419 * @returns true if a1 and a2 are both null, or if a2 is of the same length
420 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
422 public static boolean equals(double[] a1, double[] a2) {
424 // Quick test which saves comparing elements of the same array, and also
425 // catches the case that both are null.
431 // If they're the same length, test each element
432 if (a1.length == a2.length) {
433 for (int i = 0; i < a1.length; i++) {
434 if (a1[i] != a2[i]) {
441 // If a1 == null or a2 == null but not both then we will get a NullPointer
442 } catch (NullPointerException e) {
449 * Compare two float arrays for equality.
451 * @param a1 the first array to compare
452 * @param a2 the second array to compare
453 * @returns true if a1 and a2 are both null, or if a2 is of the same length
454 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
456 public static boolean equals(float[] a1, float[] a2) {
458 // Quick test which saves comparing elements of the same array, and also
459 // catches the case that both are null.
465 // If they're the same length, test each element
466 if (a1.length == a2.length) {
467 for (int i = 0; i < a1.length; i++) {
468 if (a1[i] != a2[i]) {
475 // If a1 == null or a2 == null but not both then we will get a NullPointer
476 } catch (NullPointerException e) {
483 * Compare two long arrays for equality.
485 * @param a1 the first array to compare
486 * @param a2 the second array to compare
487 * @returns true if a1 and a2 are both null, or if a2 is of the same length
488 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
490 public static boolean equals(long[] a1, long[] a2) {
492 // Quick test which saves comparing elements of the same array, and also
493 // catches the case that both are null.
499 // If they're the same length, test each element
500 if (a1.length == a2.length) {
501 for (int i = 0; i < a1.length; i++) {
502 if (a1[i] != a2[i]) {
509 // If a1 == null or a2 == null but not both then we will get a NullPointer
510 } catch (NullPointerException e) {
517 * Compare two short arrays for equality.
519 * @param a1 the first array to compare
520 * @param a2 the second array to compare
521 * @returns true if a1 and a2 are both null, or if a2 is of the same length
522 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
524 public static boolean equals(short[] a1, short[] a2) {
526 // Quick test which saves comparing elements of the same array, and also
527 // catches the case that both are null.
533 // If they're the same length, test each element
534 if (a1.length == a2.length) {
535 for (int i = 0; i < a1.length; i++) {
536 if (a1[i] != a2[i]) {
543 // If a1 == null or a2 == null but not both then we will get a NullPointer
544 } catch (NullPointerException e) {
551 * Compare two boolean arrays for equality.
553 * @param a1 the first array to compare
554 * @param a2 the second array to compare
555 * @returns true if a1 and a2 are both null, or if a2 is of the same length
556 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
558 public static boolean equals(boolean[] a1, boolean[] a2) {
560 // Quick test which saves comparing elements of the same array, and also
561 // catches the case that both are null.
567 // If they're the same length, test each element
568 if (a1.length == a2.length) {
569 for (int i = 0; i < a1.length; i++) {
570 if (a1[i] != a2[i]) {
577 // If a1 == null or a2 == null but not both then we will get a NullPointer
578 } catch (NullPointerException e) {
585 * Compare two int arrays for equality.
587 * @param a1 the first array to compare
588 * @param a2 the second array to compare
589 * @returns true if a1 and a2 are both null, or if a2 is of the same length
590 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
592 public static boolean equals(int[] a1, int[] a2) {
594 // Quick test which saves comparing elements of the same array, and also
595 // catches the case that both are null.
601 // If they're the same length, test each element
602 if (a1.length == a2.length) {
603 for (int i = 0; i < a1.length; i++) {
604 if (a1[i] != a2[i]) {
611 // If a1 == null or a2 == null but not both then we will get a NullPointer
612 } catch (NullPointerException e) {
619 * Compare two Object arrays for equality.
621 * @param a1 the first array to compare
622 * @param a2 the second array to compare
623 * @returns true if a1 and a2 are both null, or if a1 is of the same length
624 * as a2, and for each 0 <= i < a.length, a1[i] == null ? a2[i] == null :
625 * a1[i].equals(a2[i]).
627 public static boolean equals(Object[] a1, Object[] a2) {
629 // Quick test which saves comparing elements of the same array, and also
630 // catches the case that both are null.
636 // If they're the same length, test each element
637 if (a1.length == a2.length) {
638 for (int i = 0; i < a1.length; i++) {
639 if (!(a1[i] == null ? a2[i] == null : a1[i].equals(a2[i]))) {
646 // If a1 == null or a2 == null but not both then we will get a NullPointer
647 } catch (NullPointerException e) {
654 * Fill an array with a boolean value.
656 * @param a the array to fill
657 * @param val the value to fill it with
659 public static void fill(boolean[] a, boolean val) {
660 // This implementation is slightly inefficient timewise, but the extra
661 // effort over inlining it is O(1) and small, and I refuse to repeat code
662 // if it can be helped.
663 fill(a, 0, a.length, val);
667 * Fill a range of an array with a boolean value.
669 * @param a the array to fill
670 * @param fromIndex the index to fill from, inclusive
671 * @param toIndex the index to fill to, exclusive
672 * @param val the value to fill with
674 public static void fill(boolean[] a, int fromIndex, int toIndex,
676 for (int i = fromIndex; i < toIndex; i++) {
682 * Fill an array with a byte value.
684 * @param a the array to fill
685 * @param val the value to fill it with
687 public static void fill(byte[] a, byte val) {
688 // This implementation is slightly inefficient timewise, but the extra
689 // effort over inlining it is O(1) and small, and I refuse to repeat code
690 // if it can be helped.
691 fill(a, 0, a.length, val);
695 * Fill a range of an array with a byte value.
697 * @param a the array to fill
698 * @param fromIndex the index to fill from, inclusive
699 * @param toIndex the index to fill to, exclusive
700 * @param val the value to fill with
702 public static void fill(byte[] a, int fromIndex, int toIndex, byte val) {
703 for (int i = fromIndex; i < toIndex; i++) {
709 * Fill an array with a char value.
711 * @param a the array to fill
712 * @param val the value to fill it with
714 public static void fill(char[] a, char val) {
715 // This implementation is slightly inefficient timewise, but the extra
716 // effort over inlining it is O(1) and small, and I refuse to repeat code
717 // if it can be helped.
718 fill(a, 0, a.length, val);
722 * Fill a range of an array with a char value.
724 * @param a the array to fill
725 * @param fromIndex the index to fill from, inclusive
726 * @param toIndex the index to fill to, exclusive
727 * @param val the value to fill with
729 public static void fill(char[] a, int fromIndex, int toIndex, char val) {
730 for (int i = fromIndex; i < toIndex; i++) {
736 * Fill an array with a double value.
738 * @param a the array to fill
739 * @param val the value to fill it with
741 public static void fill(double[] a, double val) {
742 // This implementation is slightly inefficient timewise, but the extra
743 // effort over inlining it is O(1) and small, and I refuse to repeat code
744 // if it can be helped.
745 fill(a, 0, a.length, val);
749 * Fill a range of an array with a double value.
751 * @param a the array to fill
752 * @param fromIndex the index to fill from, inclusive
753 * @param toIndex the index to fill to, exclusive
754 * @param val the value to fill with
756 public static void fill(double[] a, int fromIndex, int toIndex, double val) {
757 for (int i = fromIndex; i < toIndex; i++) {
763 * Fill an array with a float value.
765 * @param a the array to fill
766 * @param val the value to fill it with
768 public static void fill(float[] a, float val) {
769 // This implementation is slightly inefficient timewise, but the extra
770 // effort over inlining it is O(1) and small, and I refuse to repeat code
771 // if it can be helped.
772 fill(a, 0, a.length, val);
776 * Fill a range of an array with a float value.
778 * @param a the array to fill
779 * @param fromIndex the index to fill from, inclusive
780 * @param toIndex the index to fill to, exclusive
781 * @param val the value to fill with
783 public static void fill(float[] a, int fromIndex, int toIndex, float val) {
784 for (int i = fromIndex; i < toIndex; i++) {
790 * Fill an array with an int value.
792 * @param a the array to fill
793 * @param val the value to fill it with
795 public static void fill(int[] a, int val) {
796 // This implementation is slightly inefficient timewise, but the extra
797 // effort over inlining it is O(1) and small, and I refuse to repeat code
798 // if it can be helped.
799 fill(a, 0, a.length, val);
803 * Fill a range of an array with an int value.
805 * @param a the array to fill
806 * @param fromIndex the index to fill from, inclusive
807 * @param toIndex the index to fill to, exclusive
808 * @param val the value to fill with
810 public static void fill(int[] a, int fromIndex, int toIndex, int val) {
811 for (int i = fromIndex; i < toIndex; i++) {
817 * Fill an array with a long value.
819 * @param a the array to fill
820 * @param val the value to fill it with
822 public static void fill(long[] a, long val) {
823 // This implementation is slightly inefficient timewise, but the extra
824 // effort over inlining it is O(1) and small, and I refuse to repeat code
825 // if it can be helped.
826 fill(a, 0, a.length, val);
830 * Fill a range of an array with a long value.
832 * @param a the array to fill
833 * @param fromIndex the index to fill from, inclusive
834 * @param toIndex the index to fill to, exclusive
835 * @param val the value to fill with
837 public static void fill(long[] a, int fromIndex, int toIndex, long val) {
838 for (int i = fromIndex; i < toIndex; i++) {
844 * Fill an array with a short value.
846 * @param a the array to fill
847 * @param val the value to fill it with
849 public static void fill(short[] a, short val) {
850 // This implementation is slightly inefficient timewise, but the extra
851 // effort over inlining it is O(1) and small, and I refuse to repeat code
852 // if it can be helped.
853 fill(a, 0, a.length, val);
857 * Fill a range of an array with a short value.
859 * @param a the array to fill
860 * @param fromIndex the index to fill from, inclusive
861 * @param toIndex the index to fill to, exclusive
862 * @param val the value to fill with
864 public static void fill(short[] a, int fromIndex, int toIndex, short val) {
865 for (int i = fromIndex; i < toIndex; i++) {
871 * Fill an array with an Object value.
873 * @param a the array to fill
874 * @param val the value to fill it with
875 * @exception ClassCastException if val is not an instance of the element
878 public static void fill(Object[] a, Object val) {
879 // This implementation is slightly inefficient timewise, but the extra
880 // effort over inlining it is O(1) and small, and I refuse to repeat code
881 // if it can be helped.
882 fill(a, 0, a.length, val);
886 * Fill a range of an array with an Object value.
888 * @param a the array to fill
889 * @param fromIndex the index to fill from, inclusive
890 * @param toIndex the index to fill to, exclusive
891 * @param val the value to fill with
892 * @exception ClassCastException if val is not an instance of the element
895 public static void fill(Object[] a, int fromIndex, int toIndex, Object val) {
896 for (int i = fromIndex; i < toIndex; i++) {
901 // Thanks to Paul Fisher <rao@gnu.org> for finding this quicksort algorithm
902 // as specified by Sun and porting it to Java.
905 * Sort a byte array into ascending order. The sort algorithm is an optimised
906 * quicksort, as described in Jon L. Bentley and M. Douglas McIlroy's
907 * "Engineering a Sort Function", Software-Practice and Experience, Vol.
908 * 23(11) P. 1249-1265 (November 1993). This algorithm gives nlog(n)
909 * performance on many arrays that would take quadratic time with a standard
912 * @param a the array to sort
914 public static void sort(byte[] a) {
915 qsort(a, 0, a.length);
918 private static short cmp(byte i, byte j) {
922 private static int med3(int a, int b, int c, byte[] d) {
923 return cmp(d[a], d[b]) < 0 ?
924 (cmp(d[b], d[c]) < 0 ? b : cmp(d[a], d[c]) < 0 ? c : a)
925 : (cmp(d[b], d[c]) > 0 ? b : cmp(d[a], d[c]) > 0 ? c : a);
928 private static void swap(int i, int j, byte[] a) {
934 private static void qsort(byte[] a, int start, int n) {
935 // use an insertion sort on small arrays
937 for (int i = start + 1; i < start + n; i++)
938 for (int j = i; j > 0 && cmp(a[j-1], a[j]) > 0; j--)
943 int pm = n/2; // small arrays, middle element
946 int pn = start + n-1;
948 if (n > 40) { // big arrays, pseudomedian of 9
950 pl = med3(pl, pl+s, pl+2*s, a);
951 pm = med3(pm-s, pm, pm+s, a);
952 pn = med3(pn-2*s, pn-s, pn, a);
954 pm = med3(pl, pm, pn, a); // mid-size, med of 3
957 int pa, pb, pc, pd, pv;
960 pv = start; swap(pv, pm, a);
962 pc = pd = start + n-1;
965 while (pb <= pc && (r = cmp(a[pb], a[pv])) <= 0) {
966 if (r == 0) { swap(pa, pb, a); pa++; }
969 while (pc >= pb && (r = cmp(a[pc], a[pv])) >= 0) {
970 if (r == 0) { swap(pc, pd, a); pd--; }
980 s = Math.min(pa-start, pb-pa); vecswap(start, pb-s, s, a);
981 s = Math.min(pd-pc, pn-pd-1); vecswap(pb, pn-s, s, a);
982 if ((s = pb-pa) > 1) qsort(a, start, s);
983 if ((s = pd-pc) > 1) qsort(a, pn-s, s);
986 private static void vecswap(int i, int j, int n, byte[] a) {
987 for (; n > 0; i++, j++, n--)
992 * Sort a char array into ascending order. The sort algorithm is an optimised
993 * quicksort, as described in Jon L. Bentley and M. Douglas McIlroy's
994 * "Engineering a Sort Function", Software-Practice and Experience, Vol.
995 * 23(11) P. 1249-1265 (November 1993). This algorithm gives nlog(n)
996 * performance on many arrays that would take quadratic time with a standard
999 * @param a the array to sort
1001 public static void sort(char[] a) {
1002 qsort(a, 0, a.length);
1005 private static int cmp(char i, char j) {
1009 private static int med3(int a, int b, int c, char[] d) {
1010 return cmp(d[a], d[b]) < 0 ?
1011 (cmp(d[b], d[c]) < 0 ? b : cmp(d[a], d[c]) < 0 ? c : a)
1012 : (cmp(d[b], d[c]) > 0 ? b : cmp(d[a], d[c]) > 0 ? c : a);
1015 private static void swap(int i, int j, char[] a) {
1021 private static void qsort(char[] a, int start, int n) {
1022 // use an insertion sort on small arrays
1024 for (int i = start + 1; i < start + n; i++)
1025 for (int j = i; j > 0 && cmp(a[j-1], a[j]) > 0; j--)
1030 int pm = n/2; // small arrays, middle element
1033 int pn = start + n-1;
1035 if (n > 40) { // big arrays, pseudomedian of 9
1037 pl = med3(pl, pl+s, pl+2*s, a);
1038 pm = med3(pm-s, pm, pm+s, a);
1039 pn = med3(pn-2*s, pn-s, pn, a);
1041 pm = med3(pl, pm, pn, a); // mid-size, med of 3
1044 int pa, pb, pc, pd, pv;
1047 pv = start; swap(pv, pm, a);
1049 pc = pd = start + n-1;
1052 while (pb <= pc && (r = cmp(a[pb], a[pv])) <= 0) {
1053 if (r == 0) { swap(pa, pb, a); pa++; }
1056 while (pc >= pb && (r = cmp(a[pc], a[pv])) >= 0) {
1057 if (r == 0) { swap(pc, pd, a); pd--; }
1067 s = Math.min(pa-start, pb-pa); vecswap(start, pb-s, s, a);
1068 s = Math.min(pd-pc, pn-pd-1); vecswap(pb, pn-s, s, a);
1069 if ((s = pb-pa) > 1) qsort(a, start, s);
1070 if ((s = pd-pc) > 1) qsort(a, pn-s, s);
1073 private static void vecswap(int i, int j, int n, char[] a) {
1074 for (; n > 0; i++, j++, n--)
1079 * Sort a double array into ascending order. The sort algorithm is an
1080 * optimised quicksort, as described in Jon L. Bentley and M. Douglas
1081 * McIlroy's "Engineering a Sort Function", Software-Practice and Experience,
1082 * Vol. 23(11) P. 1249-1265 (November 1993). This algorithm gives nlog(n)
1083 * performance on many arrays that would take quadratic time with a standard
1084 * quicksort. Note that this implementation, like Sun's, has undefined
1085 * behaviour if the array contains any NaN values.
1087 * @param a the array to sort
1089 public static void sort(double[] a) {
1090 qsort(a, 0, a.length);
1093 private static double cmp(double i, double j) {
1097 private static int med3(int a, int b, int c, double[] d) {
1098 return cmp(d[a], d[b]) < 0 ?
1099 (cmp(d[b], d[c]) < 0 ? b : cmp(d[a], d[c]) < 0 ? c : a)
1100 : (cmp(d[b], d[c]) > 0 ? b : cmp(d[a], d[c]) > 0 ? c : a);
1103 private static void swap(int i, int j, double[] a) {
1109 private static void qsort(double[] a, int start, int n) {
1110 // use an insertion sort on small arrays
1112 for (int i = start + 1; i < start + n; i++)
1113 for (int j = i; j > 0 && cmp(a[j-1], a[j]) > 0; j--)
1118 int pm = n/2; // small arrays, middle element
1121 int pn = start + n-1;
1123 if (n > 40) { // big arrays, pseudomedian of 9
1125 pl = med3(pl, pl+s, pl+2*s, a);
1126 pm = med3(pm-s, pm, pm+s, a);
1127 pn = med3(pn-2*s, pn-s, pn, a);
1129 pm = med3(pl, pm, pn, a); // mid-size, med of 3
1132 int pa, pb, pc, pd, pv;
1135 pv = start; swap(pv, pm, a);
1137 pc = pd = start + n-1;
1140 while (pb <= pc && (r = cmp(a[pb], a[pv])) <= 0) {
1141 if (r == 0) { swap(pa, pb, a); pa++; }
1144 while (pc >= pb && (r = cmp(a[pc], a[pv])) >= 0) {
1145 if (r == 0) { swap(pc, pd, a); pd--; }
1155 s = Math.min(pa-start, pb-pa); vecswap(start, pb-s, s, a);
1156 s = Math.min(pd-pc, pn-pd-1); vecswap(pb, pn-s, s, a);
1157 if ((s = pb-pa) > 1) qsort(a, start, s);
1158 if ((s = pd-pc) > 1) qsort(a, pn-s, s);
1161 private static void vecswap(int i, int j, int n, double[] a) {
1162 for (; n > 0; i++, j++, n--)
1167 * Sort a float array into ascending order. The sort algorithm is an
1168 * optimised quicksort, as described in Jon L. Bentley and M. Douglas
1169 * McIlroy's "Engineering a Sort Function", Software-Practice and Experience,
1170 * Vol. 23(11) P. 1249-1265 (November 1993). This algorithm gives nlog(n)
1171 * performance on many arrays that would take quadratic time with a standard
1172 * quicksort. Note that this implementation, like Sun's, has undefined
1173 * behaviour if the array contains any NaN values.
1175 * @param a the array to sort
1177 public static void sort(float[] a) {
1178 qsort(a, 0, a.length);
1181 private static float cmp(float i, float j) {
1185 private static int med3(int a, int b, int c, float[] d) {
1186 return cmp(d[a], d[b]) < 0 ?
1187 (cmp(d[b], d[c]) < 0 ? b : cmp(d[a], d[c]) < 0 ? c : a)
1188 : (cmp(d[b], d[c]) > 0 ? b : cmp(d[a], d[c]) > 0 ? c : a);
1191 private static void swap(int i, int j, float[] a) {
1197 private static void qsort(float[] a, int start, int n) {
1198 // use an insertion sort on small arrays
1200 for (int i = start + 1; i < start + n; i++)
1201 for (int j = i; j > 0 && cmp(a[j-1], a[j]) > 0; j--)
1206 int pm = n/2; // small arrays, middle element
1209 int pn = start + n-1;
1211 if (n > 40) { // big arrays, pseudomedian of 9
1213 pl = med3(pl, pl+s, pl+2*s, a);
1214 pm = med3(pm-s, pm, pm+s, a);
1215 pn = med3(pn-2*s, pn-s, pn, a);
1217 pm = med3(pl, pm, pn, a); // mid-size, med of 3
1220 int pa, pb, pc, pd, pv;
1223 pv = start; swap(pv, pm, a);
1225 pc = pd = start + n-1;
1228 while (pb <= pc && (r = cmp(a[pb], a[pv])) <= 0) {
1229 if (r == 0) { swap(pa, pb, a); pa++; }
1232 while (pc >= pb && (r = cmp(a[pc], a[pv])) >= 0) {
1233 if (r == 0) { swap(pc, pd, a); pd--; }
1243 s = Math.min(pa-start, pb-pa); vecswap(start, pb-s, s, a);
1244 s = Math.min(pd-pc, pn-pd-1); vecswap(pb, pn-s, s, a);
1245 if ((s = pb-pa) > 1) qsort(a, start, s);
1246 if ((s = pd-pc) > 1) qsort(a, pn-s, s);
1249 private static void vecswap(int i, int j, int n, float[] a) {
1250 for (; n > 0; i++, j++, n--)
1255 * Sort an int array into ascending order. The sort algorithm is an optimised
1256 * quicksort, as described in Jon L. Bentley and M. Douglas McIlroy's
1257 * "Engineering a Sort Function", Software-Practice and Experience, Vol.
1258 * 23(11) P. 1249-1265 (November 1993). This algorithm gives nlog(n)
1259 * performance on many arrays that would take quadratic time with a standard
1262 * @param a the array to sort
1264 public static void sort(int[] a) {
1265 qsort(a, 0, a.length);
1268 private static long cmp(int i, int j) {
1269 return (long)i-(long)j;
1272 private static int med3(int a, int b, int c, int[] d) {
1273 return cmp(d[a], d[b]) < 0 ?
1274 (cmp(d[b], d[c]) < 0 ? b : cmp(d[a], d[c]) < 0 ? c : a)
1275 : (cmp(d[b], d[c]) > 0 ? b : cmp(d[a], d[c]) > 0 ? c : a);
1278 private static void swap(int i, int j, int[] a) {
1284 private static void qsort(int[] a, int start, int n) {
1285 // use an insertion sort on small arrays
1287 for (int i = start + 1; i < start + n; i++)
1288 for (int j = i; j > 0 && cmp(a[j-1], a[j]) > 0; j--)
1293 int pm = n/2; // small arrays, middle element
1296 int pn = start + n-1;
1298 if (n > 40) { // big arrays, pseudomedian of 9
1300 pl = med3(pl, pl+s, pl+2*s, a);
1301 pm = med3(pm-s, pm, pm+s, a);
1302 pn = med3(pn-2*s, pn-s, pn, a);
1304 pm = med3(pl, pm, pn, a); // mid-size, med of 3
1307 int pa, pb, pc, pd, pv;
1310 pv = start; swap(pv, pm, a);
1312 pc = pd = start + n-1;
1315 while (pb <= pc && (r = cmp(a[pb], a[pv])) <= 0) {
1316 if (r == 0) { swap(pa, pb, a); pa++; }
1319 while (pc >= pb && (r = cmp(a[pc], a[pv])) >= 0) {
1320 if (r == 0) { swap(pc, pd, a); pd--; }
1330 s = Math.min(pa-start, pb-pa); vecswap(start, pb-s, s, a);
1331 s = Math.min(pd-pc, pn-pd-1); vecswap(pb, pn-s, s, a);
1332 if ((s = pb-pa) > 1) qsort(a, start, s);
1333 if ((s = pd-pc) > 1) qsort(a, pn-s, s);
1336 private static void vecswap(int i, int j, int n, int[] a) {
1337 for (; n > 0; i++, j++, n--)
1342 * Sort a long array into ascending order. The sort algorithm is an optimised
1343 * quicksort, as described in Jon L. Bentley and M. Douglas McIlroy's
1344 * "Engineering a Sort Function", Software-Practice and Experience, Vol.
1345 * 23(11) P. 1249-1265 (November 1993). This algorithm gives nlog(n)
1346 * performance on many arrays that would take quadratic time with a standard
1349 * @param a the array to sort
1351 public static void sort(long[] a) {
1352 qsort(a, 0, a.length);
1355 // The "cmp" method has been removed from here and replaced with direct
1356 // compares in situ, to avoid problems with overflow if the difference
1357 // between two numbers is bigger than a long will hold.
1358 // One particular change as a result is the use of r1 and r2 in qsort
1360 private static int med3(int a, int b, int c, long[] d) {
1361 return d[a] < d[b] ?
1362 (d[b] < d[c] ? b : d[a] < d[c] ? c : a)
1363 : (d[b] > d[c] ? b : d[a] > d[c] ? c : a);
1366 private static void swap(int i, int j, long[] a) {
1372 private static void qsort(long[] a, int start, int n) {
1373 // use an insertion sort on small arrays
1375 for (int i = start + 1; i < start + n; i++)
1376 for (int j = i; j > 0 && a[j-1] > a[j]; j--)
1381 int pm = n/2; // small arrays, middle element
1384 int pn = start + n-1;
1386 if (n > 40) { // big arrays, pseudomedian of 9
1388 pl = med3(pl, pl+s, pl+2*s, a);
1389 pm = med3(pm-s, pm, pm+s, a);
1390 pn = med3(pn-2*s, pn-s, pn, a);
1392 pm = med3(pl, pm, pn, a); // mid-size, med of 3
1395 int pa, pb, pc, pd, pv;
1398 pv = start; swap(pv, pm, a);
1400 pc = pd = start + n-1;
1403 while (pb <= pc && (r1 = a[pb]) <= (r2 = a[pv])) {
1404 if (r1 == r2) { swap(pa, pb, a); pa++; }
1407 while (pc >= pb && (r1 = a[pc]) >= (r2 = a[pv])) {
1408 if (r1 == r2) { swap(pc, pd, a); pd--; }
1418 s = Math.min(pa-start, pb-pa); vecswap(start, pb-s, s, a);
1419 s = Math.min(pd-pc, pn-pd-1); vecswap(pb, pn-s, s, a);
1420 if ((s = pb-pa) > 1) qsort(a, start, s);
1421 if ((s = pd-pc) > 1) qsort(a, pn-s, s);
1424 private static void vecswap(int i, int j, int n, long[] a) {
1425 for (; n > 0; i++, j++, n--)
1430 * Sort a short array into ascending order. The sort algorithm is an
1431 * optimised quicksort, as described in Jon L. Bentley and M. Douglas
1432 * McIlroy's "Engineering a Sort Function", Software-Practice and Experience,
1433 * Vol. 23(11) P. 1249-1265 (November 1993). This algorithm gives nlog(n)
1434 * performance on many arrays that would take quadratic time with a standard
1437 * @param a the array to sort
1439 public static void sort(short[] a) {
1440 qsort(a, 0, a.length);
1443 private static int cmp(short i, short j) {
1447 private static int med3(int a, int b, int c, short[] d) {
1448 return cmp(d[a], d[b]) < 0 ?
1449 (cmp(d[b], d[c]) < 0 ? b : cmp(d[a], d[c]) < 0 ? c : a)
1450 : (cmp(d[b], d[c]) > 0 ? b : cmp(d[a], d[c]) > 0 ? c : a);
1453 private static void swap(int i, int j, short[] a) {
1459 private static void qsort(short[] a, int start, int n) {
1460 // use an insertion sort on small arrays
1462 for (int i = start + 1; i < start + n; i++)
1463 for (int j = i; j > 0 && cmp(a[j-1], a[j]) > 0; j--)
1468 int pm = n/2; // small arrays, middle element
1471 int pn = start + n-1;
1473 if (n > 40) { // big arrays, pseudomedian of 9
1475 pl = med3(pl, pl+s, pl+2*s, a);
1476 pm = med3(pm-s, pm, pm+s, a);
1477 pn = med3(pn-2*s, pn-s, pn, a);
1479 pm = med3(pl, pm, pn, a); // mid-size, med of 3
1482 int pa, pb, pc, pd, pv;
1485 pv = start; swap(pv, pm, a);
1487 pc = pd = start + n-1;
1490 while (pb <= pc && (r = cmp(a[pb], a[pv])) <= 0) {
1491 if (r == 0) { swap(pa, pb, a); pa++; }
1494 while (pc >= pb && (r = cmp(a[pc], a[pv])) >= 0) {
1495 if (r == 0) { swap(pc, pd, a); pd--; }
1505 s = Math.min(pa-start, pb-pa); vecswap(start, pb-s, s, a);
1506 s = Math.min(pd-pc, pn-pd-1); vecswap(pb, pn-s, s, a);
1507 if ((s = pb-pa) > 1) qsort(a, start, s);
1508 if ((s = pd-pc) > 1) qsort(a, pn-s, s);
1511 private static void vecswap(int i, int j, int n, short[] a) {
1512 for (; n > 0; i++, j++, n--)
1517 * The bulk of the work for the object sort routines. In general,
1518 * the code attempts to be simple rather than fast, the idea being
1519 * that a good optimising JIT will be able to optimise it better
1520 * than I can, and if I try it will make it more confusing for the
1523 private static void mergeSort(Object[] a, int from, int to, Comparator c)
1525 // First presort the array in chunks of length 6 with insertion sort.
1526 // mergesort would give too much overhead for this length.
1527 for (int chunk = from; chunk < to; chunk += 6)
1529 int end = Math.min(chunk+6, to);
1530 for (int i = chunk + 1; i < end; i++)
1532 if (c.compare(a[i-1], a[i]) > 0)
1534 // not already sorted
1542 while (j>chunk && c.compare(a[j-1], elem) > 0);
1548 int len = to - from;
1549 // If length is smaller or equal 6 we are done.
1554 Object[] dest = new Object[len];
1555 Object[] t = null; // t is used for swapping src and dest
1557 // The difference of the fromIndex of the src and dest array.
1558 int srcDestDiff = -from;
1560 // The merges are done in this loop
1561 for (int size = 6; size < len; size <<= 1)
1563 for (int start = from; start < to; start += size << 1)
1565 // mid ist the start of the second sublist;
1566 // end the start of the next sublist (or end of array).
1567 int mid = start + size;
1568 int end = Math.min(to, mid + size);
1570 // The second list is empty or the elements are already in
1571 // order - no need to merge
1572 if (mid >= end || c.compare(src[mid - 1], src[mid]) <= 0) {
1573 System.arraycopy(src, start,
1574 dest, start + srcDestDiff, end - start);
1576 // The two halves just need swapping - no need to merge
1577 } else if (c.compare(src[start], src[end - 1]) > 0) {
1578 System.arraycopy(src, start,
1579 dest, end - size + srcDestDiff, size);
1580 System.arraycopy(src, mid,
1581 dest, start + srcDestDiff, end - mid);
1584 // Declare a lot of variables to save repeating
1585 // calculations. Hopefully a decent JIT will put these
1586 // in registers and make this fast
1589 int i = start + srcDestDiff;
1591 // The main merge loop; terminates as soon as either
1593 while (p1 < mid && p2 < end)
1596 src[c.compare(src[p1], src[p2]) <= 0 ? p1++ : p2++];
1599 // Finish up by copying the remainder of whichever half
1602 System.arraycopy(src, p1, dest, i, mid - p1);
1604 System.arraycopy(src, p2, dest, i, end - p2);
1607 // swap src and dest ready for the next merge
1608 t = src; src = dest; dest = t;
1609 from += srcDestDiff;
1611 srcDestDiff = -srcDestDiff;
1614 // make sure the result ends up back in the right place. Note
1615 // that src and dest may have been swapped above, so src
1616 // contains the sorted array.
1619 // Note that from == 0.
1620 System.arraycopy(src, 0, a, srcDestDiff, to);
1625 * Sort an array of Objects according to their natural ordering. The sort is
1626 * guaranteed to be stable, that is, equal elements will not be reordered.
1627 * The sort algorithm is a mergesort with the merge omitted if the last
1628 * element of one half comes before the first element of the other half. This
1629 * algorithm gives guaranteed O(nlog(n)) time, at the expense of making a
1630 * copy of the array.
1632 * @param a the array to be sorted
1633 * @exception ClassCastException if any two elements are not mutually
1635 * @exception NullPointerException if an element is null (since
1636 * null.compareTo cannot work)
1638 public static void sort(Object[] a) {
1639 mergeSort(a, 0, a.length, defaultComparator);
1643 * Sort an array of Objects according to a Comparator. The sort is
1644 * guaranteed to be stable, that is, equal elements will not be reordered.
1645 * The sort algorithm is a mergesort with the merge omitted if the last
1646 * element of one half comes before the first element of the other half. This
1647 * algorithm gives guaranteed O(nlog(n)) time, at the expense of making a
1648 * copy of the array.
1650 * @param a the array to be sorted
1651 * @param c a Comparator to use in sorting the array
1652 * @exception ClassCastException if any two elements are not mutually
1653 * comparable by the Comparator provided
1655 public static void sort(Object[] a, Comparator c) {
1656 mergeSort(a, 0, a.length, c);
1660 * Sort an array of Objects according to their natural ordering. The sort is
1661 * guaranteed to be stable, that is, equal elements will not be reordered.
1662 * The sort algorithm is a mergesort with the merge omitted if the last
1663 * element of one half comes before the first element of the other half. This
1664 * algorithm gives guaranteed O(nlog(n)) time, at the expense of making a
1665 * copy of the array.
1667 * @param a the array to be sorted
1668 * @param fromIndex the index of the first element to be sorted.
1669 * @param toIndex the index of the last element to be sorted plus one.
1670 * @exception ClassCastException if any two elements are not mutually
1671 * comparable by the Comparator provided
1672 * @exception ArrayIndexOutOfBoundsException, if fromIndex and toIndex
1674 * @exception IllegalArgumentException if fromIndex > toIndex
1676 public static void sort(Object[] a, int fromIndex,
1678 if (fromIndex > toIndex)
1679 throw new IllegalArgumentException("fromIndex "+fromIndex
1680 +" > toIndex "+toIndex);
1681 mergeSort(a, fromIndex, toIndex, defaultComparator);
1685 * Sort an array of Objects according to a Comparator. The sort is
1686 * guaranteed to be stable, that is, equal elements will not be reordered.
1687 * The sort algorithm is a mergesort with the merge omitted if the last
1688 * element of one half comes before the first element of the other half. This
1689 * algorithm gives guaranteed O(nlog(n)) time, at the expense of making a
1690 * copy of the array.
1692 * @param a the array to be sorted
1693 * @param fromIndex the index of the first element to be sorted.
1694 * @param toIndex the index of the last element to be sorted plus one.
1695 * @param c a Comparator to use in sorting the array
1696 * @exception ClassCastException if any two elements are not mutually
1697 * comparable by the Comparator provided
1698 * @exception ArrayIndexOutOfBoundsException, if fromIndex and toIndex
1700 * @exception IllegalArgumentException if fromIndex > toIndex
1702 public static void sort(Object[] a, int fromIndex,
1703 int toIndex, Comparator c) {
1704 if (fromIndex > toIndex)
1705 throw new IllegalArgumentException("fromIndex "+fromIndex
1706 +" > toIndex "+toIndex);
1707 mergeSort(a, fromIndex, toIndex, c);
1711 * Returns a list "view" of the specified array. This method is intended to
1712 * make it easy to use the Collections API with existing array-based APIs and
1715 * @param a the array to return a view of
1716 * @returns a fixed-size list, changes to which "write through" to the array
1718 public static List asList(final Object[] a) {
1721 throw new NullPointerException();
1724 return new ListImpl( a );
1729 * Inner class used by asList(Object[]) to provide a list interface
1730 * to an array. The methods are all simple enough to be self documenting.
1731 * Note: When Sun fully specify serialized forms, this class will have to
1734 private static class ListImpl extends AbstractList {
1736 ListImpl(Object[] a) {
1740 public Object get(int index) {
1748 public Object set(int index, Object element) {
1749 Object old = a[index];