1 /* Arrays.java -- Utility class with methods to operate on arrays
2 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
3 Free Software Foundation, Inc.
5 This file is part of GNU Classpath.
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING. If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library. Thus, the terms and
24 conditions of the GNU General Public License cover the whole
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module. An independent module is a module which is not derived from
34 or based on this library. If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so. If you do not wish to do so, delete this
37 exception statement from your version. */
42 import java.io.Serializable;
43 import java.lang.reflect.Array;
46 * This class contains various static utility methods performing operations on
47 * arrays, and a method to provide a List "view" of an array to facilitate
48 * using arrays with Collection-based APIs. All methods throw a
49 * {@link NullPointerException} if the parameter array is null.
52 * Implementations may use their own algorithms, but must obey the general
53 * properties; for example, the sort must be stable and n*log(n) complexity.
54 * Sun's implementation of sort, and therefore ours, is a tuned quicksort,
55 * adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort
56 * Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265
57 * (November 1993). This algorithm offers n*log(n) performance on many data
58 * sets that cause other quicksorts to degrade to quadratic performance.
60 * @author Original author unknown
61 * @author Bryce McKinlay
62 * @author Eric Blake (ebb9@email.byu.edu)
66 * @status updated to 1.4
71 * This class is non-instantiable.
80 * Perform a binary search of a byte array for a key. The array must be
81 * sorted (as by the sort() method) - if it is not, the behaviour of this
82 * method is undefined, and may be an infinite loop. If the array contains
83 * the key more than once, any one of them may be found. Note: although the
84 * specification allows for an infinite loop if the array is unsorted, it
85 * will not happen in this implementation.
87 * @param a the array to search (must be sorted)
88 * @param key the value to search for
89 * @return the index at which the key was found, or -n-1 if it was not
90 * found, where n is the index of the first value higher than key or
91 * a.length if there is no such value.
93 public static int binarySearch(byte[] a, byte key)
96 int hi = a.length - 1;
100 mid = (low + hi) >>> 1;
101 final byte d = a[mid];
107 // This gets the insertion point right on the last loop.
114 * Perform a binary search of a char array for a key. The array must be
115 * sorted (as by the sort() method) - if it is not, the behaviour of this
116 * method is undefined, and may be an infinite loop. If the array contains
117 * the key more than once, any one of them may be found. Note: although the
118 * specification allows for an infinite loop if the array is unsorted, it
119 * will not happen in this implementation.
121 * @param a the array to search (must be sorted)
122 * @param key the value to search for
123 * @return the index at which the key was found, or -n-1 if it was not
124 * found, where n is the index of the first value higher than key or
125 * a.length if there is no such value.
127 public static int binarySearch(char[] a, char key)
130 int hi = a.length - 1;
134 mid = (low + hi) >>> 1;
135 final char d = a[mid];
141 // This gets the insertion point right on the last loop.
148 * Perform a binary search of a short array for a key. The array must be
149 * sorted (as by the sort() method) - if it is not, the behaviour of this
150 * method is undefined, and may be an infinite loop. If the array contains
151 * the key more than once, any one of them may be found. Note: although the
152 * specification allows for an infinite loop if the array is unsorted, it
153 * will not happen in this implementation.
155 * @param a the array to search (must be sorted)
156 * @param key the value to search for
157 * @return the index at which the key was found, or -n-1 if it was not
158 * found, where n is the index of the first value higher than key or
159 * a.length if there is no such value.
161 public static int binarySearch(short[] a, short key)
164 int hi = a.length - 1;
168 mid = (low + hi) >>> 1;
169 final short d = a[mid];
175 // 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 * @return 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)
198 int hi = a.length - 1;
202 mid = (low + hi) >>> 1;
203 final int d = a[mid];
209 // This gets the insertion point right on the last loop.
216 * Perform a binary search of a long array for a key. The array must be
217 * sorted (as by the sort() method) - if it is not, the behaviour of this
218 * method is undefined, and may be an infinite loop. If the array contains
219 * the key more than once, any one of them may be found. Note: although the
220 * specification allows for an infinite loop if the array is unsorted, it
221 * will not happen in this implementation.
223 * @param a the array to search (must be sorted)
224 * @param key the value to search for
225 * @return the index at which the key was found, or -n-1 if it was not
226 * found, where n is the index of the first value higher than key or
227 * a.length if there is no such value.
229 public static int binarySearch(long[] a, long key)
232 int hi = a.length - 1;
236 mid = (low + hi) >>> 1;
237 final long d = a[mid];
243 // This gets the insertion point right on the last loop.
250 * Perform a binary search of a float array for a key. The array must be
251 * sorted (as by the sort() method) - if it is not, the behaviour of this
252 * method is undefined, and may be an infinite loop. If the array contains
253 * the key more than once, any one of them may be found. Note: although the
254 * specification allows for an infinite loop if the array is unsorted, it
255 * will not happen in this implementation.
257 * @param a the array to search (must be sorted)
258 * @param key the value to search for
259 * @return the index at which the key was found, or -n-1 if it was not
260 * found, where n is the index of the first value higher than key or
261 * a.length if there is no such value.
263 public static int binarySearch(float[] a, float key)
265 // Must use Float.compare to take into account NaN, +-0.
267 int hi = a.length - 1;
271 mid = (low + hi) >>> 1;
272 final int r = Float.compare(a[mid], key);
278 // This gets the insertion point right on the last loop
285 * Perform a binary search of a double array for a key. The array must be
286 * sorted (as by the sort() method) - if it is not, the behaviour of this
287 * method is undefined, and may be an infinite loop. If the array contains
288 * the key more than once, any one of them may be found. Note: although the
289 * specification allows for an infinite loop if the array is unsorted, it
290 * will not happen in this implementation.
292 * @param a the array to search (must be sorted)
293 * @param key the value to search for
294 * @return the index at which the key was found, or -n-1 if it was not
295 * found, where n is the index of the first value higher than key or
296 * a.length if there is no such value.
298 public static int binarySearch(double[] a, double key)
300 // Must use Double.compare to take into account NaN, +-0.
302 int hi = a.length - 1;
306 mid = (low + hi) >>> 1;
307 final int r = Double.compare(a[mid], key);
313 // This gets the insertion point right on the last loop
320 * Perform a binary search of an Object array for a key, using the natural
321 * ordering of the elements. The array must be sorted (as by the sort()
322 * method) - if it is not, the behaviour of this method is undefined, and may
323 * be an infinite loop. Further, the key must be comparable with every item
324 * in the array. If the array contains the key more than once, any one of
325 * them may be found. Note: although the specification allows for an infinite
326 * loop if the array is unsorted, it will not happen in this (JCL)
329 * @param a the array to search (must be sorted)
330 * @param key the value to search for
331 * @return the index at which the key was found, or -n-1 if it was not
332 * found, where n is the index of the first value higher than key or
333 * a.length if there is no such value.
334 * @throws ClassCastException if key could not be compared with one of the
336 * @throws NullPointerException if a null element in a is compared
338 public static int binarySearch(Object[] a, Object key)
340 return binarySearch(a, key, null);
344 * Perform a binary search of an Object array for a key, using a supplied
345 * Comparator. The array must be sorted (as by the sort() method with the
346 * same Comparator) - if it is not, the behaviour of this method is
347 * undefined, and may be an infinite loop. Further, the key must be
348 * comparable with every item in the array. If the array contains the key
349 * more than once, any one of them may be found. Note: although the
350 * specification allows for an infinite loop if the array is unsorted, it
351 * will not happen in this (JCL) implementation.
353 * @param a the array to search (must be sorted)
354 * @param key the value to search for
355 * @param c the comparator by which the array is sorted; or null to
356 * use the elements' natural order
357 * @return the index at which the key was found, or -n-1 if it was not
358 * found, where n is the index of the first value higher than key or
359 * a.length if there is no such value.
360 * @throws ClassCastException if key could not be compared with one of the
362 * @throws NullPointerException if a null element is compared with natural
363 * ordering (only possible when c is null)
365 public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
368 int hi = a.length - 1;
372 mid = (low + hi) >>> 1;
373 final int d = Collections.compare(key, a[mid], c);
379 // This gets the insertion point right on the last loop
388 * Compare two boolean arrays for equality.
390 * @param a1 the first array to compare
391 * @param a2 the second array to compare
392 * @return true if a1 and a2 are both null, or if a2 is of the same length
393 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
395 public static boolean equals(boolean[] a1, boolean[] a2)
397 // Quick test which saves comparing elements of the same array, and also
398 // catches the case that both are null.
402 if (null == a1 || null == a2)
405 // If they're the same length, test each element
406 if (a1.length == a2.length)
418 * Compare two byte arrays for equality.
420 * @param a1 the first array to compare
421 * @param a2 the second array to compare
422 * @return true if a1 and a2 are both null, or if a2 is of the same length
423 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
425 public static boolean equals(byte[] a1, byte[] a2)
427 // Quick test which saves comparing elements of the same array, and also
428 // catches the case that both are null.
432 if (null == a1 || null == a2)
435 // If they're the same length, test each element
436 if (a1.length == a2.length)
448 * Compare two char arrays for equality.
450 * @param a1 the first array to compare
451 * @param a2 the second array to compare
452 * @return true if a1 and a2 are both null, or if a2 is of the same length
453 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
455 public static boolean equals(char[] a1, char[] a2)
457 // Quick test which saves comparing elements of the same array, and also
458 // catches the case that both are null.
462 if (null == a1 || null == a2)
465 // If they're the same length, test each element
466 if (a1.length == a2.length)
478 * Compare two short arrays for equality.
480 * @param a1 the first array to compare
481 * @param a2 the second array to compare
482 * @return true if a1 and a2 are both null, or if a2 is of the same length
483 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
485 public static boolean equals(short[] a1, short[] a2)
487 // Quick test which saves comparing elements of the same array, and also
488 // catches the case that both are null.
492 if (null == a1 || null == a2)
495 // If they're the same length, test each element
496 if (a1.length == a2.length)
508 * Compare two int arrays for equality.
510 * @param a1 the first array to compare
511 * @param a2 the second array to compare
512 * @return true if a1 and a2 are both null, or if a2 is of the same length
513 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
515 public static boolean equals(int[] a1, int[] a2)
517 // Quick test which saves comparing elements of the same array, and also
518 // catches the case that both are null.
522 if (null == a1 || null == a2)
525 // If they're the same length, test each element
526 if (a1.length == a2.length)
538 * Compare two long arrays for equality.
540 * @param a1 the first array to compare
541 * @param a2 the second array to compare
542 * @return true if a1 and a2 are both null, or if a2 is of the same length
543 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
545 public static boolean equals(long[] a1, long[] a2)
547 // Quick test which saves comparing elements of the same array, and also
548 // catches the case that both are null.
552 if (null == a1 || null == a2)
555 // If they're the same length, test each element
556 if (a1.length == a2.length)
568 * Compare two float arrays for equality.
570 * @param a1 the first array to compare
571 * @param a2 the second array to compare
572 * @return true if a1 and a2 are both null, or if a2 is of the same length
573 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
575 public static boolean equals(float[] a1, float[] a2)
577 // Quick test which saves comparing elements of the same array, and also
578 // catches the case that both are null.
582 if (null == a1 || null == a2)
585 // Must use Float.compare to take into account NaN, +-0.
586 // If they're the same length, test each element
587 if (a1.length == a2.length)
591 if (Float.compare(a1[i], a2[i]) != 0)
599 * Compare two double arrays for equality.
601 * @param a1 the first array to compare
602 * @param a2 the second array to compare
603 * @return true if a1 and a2 are both null, or if a2 is of the same length
604 * as a1, and for each 0 <= i < a1.length, a1[i] == a2[i]
606 public static boolean equals(double[] a1, double[] a2)
608 // Quick test which saves comparing elements of the same array, and also
609 // catches the case that both are null.
613 if (null == a1 || null == a2)
616 // Must use Double.compare to take into account NaN, +-0.
617 // If they're the same length, test each element
618 if (a1.length == a2.length)
622 if (Double.compare(a1[i], a2[i]) != 0)
630 * Compare two Object arrays for equality.
632 * @param a1 the first array to compare
633 * @param a2 the second array to compare
634 * @return true if a1 and a2 are both null, or if a1 is of the same length
635 * as a2, and for each 0 <= i < a.length, a1[i] == null ?
636 * a2[i] == null : a1[i].equals(a2[i]).
638 public static boolean equals(Object[] a1, Object[] a2)
640 // Quick test which saves comparing elements of the same array, and also
641 // catches the case that both are null.
645 if (null == a1 || null == a2)
648 // If they're the same length, test each element
649 if (a1.length == a2.length)
653 if (! AbstractCollection.equals(a1[i], a2[i]))
663 * Fill an array with a boolean value.
665 * @param a the array to fill
666 * @param val the value to fill it with
668 public static void fill(boolean[] a, boolean val)
670 fill(a, 0, a.length, val);
674 * Fill a range of an array with a boolean value.
676 * @param a the array to fill
677 * @param fromIndex the index to fill from, inclusive
678 * @param toIndex the index to fill to, exclusive
679 * @param val the value to fill with
680 * @throws IllegalArgumentException if fromIndex > toIndex
681 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
682 * || toIndex > a.length
684 public static void fill(boolean[] a, int fromIndex, int toIndex, boolean val)
686 if (fromIndex > toIndex)
687 throw new IllegalArgumentException();
688 for (int i = fromIndex; i < toIndex; i++)
693 * Fill an array with a byte value.
695 * @param a the array to fill
696 * @param val the value to fill it with
698 public static void fill(byte[] a, byte val)
700 fill(a, 0, a.length, val);
704 * Fill a range of an array with a byte value.
706 * @param a the array to fill
707 * @param fromIndex the index to fill from, inclusive
708 * @param toIndex the index to fill to, exclusive
709 * @param val the value to fill with
710 * @throws IllegalArgumentException if fromIndex > toIndex
711 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
712 * || toIndex > a.length
714 public static void fill(byte[] a, int fromIndex, int toIndex, byte val)
716 if (fromIndex > toIndex)
717 throw new IllegalArgumentException();
718 for (int i = fromIndex; i < toIndex; i++)
723 * Fill an array with a char value.
725 * @param a the array to fill
726 * @param val the value to fill it with
728 public static void fill(char[] a, char val)
730 fill(a, 0, a.length, val);
734 * Fill a range of an array with a char value.
736 * @param a the array to fill
737 * @param fromIndex the index to fill from, inclusive
738 * @param toIndex the index to fill to, exclusive
739 * @param val the value to fill with
740 * @throws IllegalArgumentException if fromIndex > toIndex
741 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
742 * || toIndex > a.length
744 public static void fill(char[] a, int fromIndex, int toIndex, char val)
746 if (fromIndex > toIndex)
747 throw new IllegalArgumentException();
748 for (int i = fromIndex; i < toIndex; i++)
753 * Fill an array with a short value.
755 * @param a the array to fill
756 * @param val the value to fill it with
758 public static void fill(short[] a, short val)
760 fill(a, 0, a.length, val);
764 * Fill a range of an array with a short value.
766 * @param a the array to fill
767 * @param fromIndex the index to fill from, inclusive
768 * @param toIndex the index to fill to, exclusive
769 * @param val the value to fill with
770 * @throws IllegalArgumentException if fromIndex > toIndex
771 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
772 * || toIndex > a.length
774 public static void fill(short[] a, int fromIndex, int toIndex, short val)
776 if (fromIndex > toIndex)
777 throw new IllegalArgumentException();
778 for (int i = fromIndex; i < toIndex; i++)
783 * Fill an array with an int value.
785 * @param a the array to fill
786 * @param val the value to fill it with
788 public static void fill(int[] a, int val)
790 fill(a, 0, a.length, val);
794 * Fill a range of an array with an int value.
796 * @param a the array to fill
797 * @param fromIndex the index to fill from, inclusive
798 * @param toIndex the index to fill to, exclusive
799 * @param val the value to fill with
800 * @throws IllegalArgumentException if fromIndex > toIndex
801 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
802 * || toIndex > a.length
804 public static void fill(int[] a, int fromIndex, int toIndex, int val)
806 if (fromIndex > toIndex)
807 throw new IllegalArgumentException();
808 for (int i = fromIndex; i < toIndex; i++)
813 * Fill an array with a long value.
815 * @param a the array to fill
816 * @param val the value to fill it with
818 public static void fill(long[] a, long val)
820 fill(a, 0, a.length, val);
824 * Fill a range of an array with a long value.
826 * @param a the array to fill
827 * @param fromIndex the index to fill from, inclusive
828 * @param toIndex the index to fill to, exclusive
829 * @param val the value to fill with
830 * @throws IllegalArgumentException if fromIndex > toIndex
831 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
832 * || toIndex > a.length
834 public static void fill(long[] a, int fromIndex, int toIndex, long val)
836 if (fromIndex > toIndex)
837 throw new IllegalArgumentException();
838 for (int i = fromIndex; i < toIndex; i++)
843 * Fill an array with a float value.
845 * @param a the array to fill
846 * @param val the value to fill it with
848 public static void fill(float[] a, float val)
850 fill(a, 0, a.length, val);
854 * Fill a range of an array with a float value.
856 * @param a the array to fill
857 * @param fromIndex the index to fill from, inclusive
858 * @param toIndex the index to fill to, exclusive
859 * @param val the value to fill with
860 * @throws IllegalArgumentException if fromIndex > toIndex
861 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
862 * || toIndex > a.length
864 public static void fill(float[] a, int fromIndex, int toIndex, float val)
866 if (fromIndex > toIndex)
867 throw new IllegalArgumentException();
868 for (int i = fromIndex; i < toIndex; i++)
873 * Fill an array with a double value.
875 * @param a the array to fill
876 * @param val the value to fill it with
878 public static void fill(double[] a, double val)
880 fill(a, 0, a.length, val);
884 * Fill a range of an array with a double value.
886 * @param a the array to fill
887 * @param fromIndex the index to fill from, inclusive
888 * @param toIndex the index to fill to, exclusive
889 * @param val the value to fill with
890 * @throws IllegalArgumentException if fromIndex > toIndex
891 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
892 * || toIndex > a.length
894 public static void fill(double[] a, int fromIndex, int toIndex, double val)
896 if (fromIndex > toIndex)
897 throw new IllegalArgumentException();
898 for (int i = fromIndex; i < toIndex; i++)
903 * Fill an array with an Object value.
905 * @param a the array to fill
906 * @param val the value to fill it with
907 * @throws ClassCastException if val is not an instance of the element
910 public static void fill(Object[] a, Object val)
912 fill(a, 0, a.length, val);
916 * Fill a range of an array with an Object value.
918 * @param a the array to fill
919 * @param fromIndex the index to fill from, inclusive
920 * @param toIndex the index to fill to, exclusive
921 * @param val the value to fill with
922 * @throws ClassCastException if val is not an instance of the element
924 * @throws IllegalArgumentException if fromIndex > toIndex
925 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
926 * || toIndex > a.length
928 public static void fill(Object[] a, int fromIndex, int toIndex, Object val)
930 if (fromIndex > toIndex)
931 throw new IllegalArgumentException();
932 for (int i = fromIndex; i < toIndex; i++)
938 // Thanks to Paul Fisher (rao@gnu.org) for finding this quicksort algorithm
939 // as specified by Sun and porting it to Java. The algorithm is an optimised
940 // quicksort, as described in Jon L. Bentley and M. Douglas McIlroy's
941 // "Engineering a Sort Function", Software-Practice and Experience, Vol.
942 // 23(11) P. 1249-1265 (November 1993). This algorithm gives n*log(n)
943 // performance on many arrays that would take quadratic time with a standard
947 * Performs a stable sort on the elements, arranging them according to their
950 * @param a the byte array to sort
952 public static void sort(byte[] a)
954 qsort(a, 0, a.length);
958 * Performs a stable sort on the elements, arranging them according to their
961 * @param a the byte array to sort
962 * @param fromIndex the first index to sort (inclusive)
963 * @param toIndex the last index to sort (exclusive)
964 * @throws IllegalArgumentException if fromIndex > toIndex
965 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
966 * || toIndex > a.length
968 public static void sort(byte[] a, int fromIndex, int toIndex)
970 if (fromIndex > toIndex)
971 throw new IllegalArgumentException();
973 throw new ArrayIndexOutOfBoundsException();
974 qsort(a, fromIndex, toIndex - fromIndex);
978 * Finds the index of the median of three array elements.
980 * @param a the first index
981 * @param b the second index
982 * @param c the third index
984 * @return the index (a, b, or c) which has the middle value of the three
986 private static int med3(int a, int b, int c, byte[] d)
989 ? (d[b] < d[c] ? b : d[a] < d[c] ? c : a)
990 : (d[b] > d[c] ? b : d[a] > d[c] ? c : a));
994 * Swaps the elements at two locations of an array
996 * @param i the first index
997 * @param j the second index
1000 private static void swap(int i, int j, byte[] a)
1008 * Swaps two ranges of an array.
1010 * @param i the first range start
1011 * @param j the second range start
1012 * @param n the element count
1013 * @param a the array
1015 private static void vecswap(int i, int j, int n, byte[] a)
1017 for ( ; n > 0; i++, j++, n--)
1022 * Performs a recursive modified quicksort.
1024 * @param array the array to sort
1025 * @param from the start index (inclusive)
1026 * @param count the number of elements to sort
1028 private static void qsort(byte[] array, int from, int count)
1030 // Use an insertion sort on small arrays.
1033 for (int i = from + 1; i < from + count; i++)
1034 for (int j = i; j > from && array[j - 1] > array[j]; j--)
1035 swap(j, j - 1, array);
1039 // Determine a good median element.
1040 int mid = count / 2;
1042 int hi = from + count - 1;
1045 { // big arrays, pseudomedian of 9
1047 lo = med3(lo, lo + s, lo + 2 * s, array);
1048 mid = med3(mid - s, mid, mid + s, array);
1049 hi = med3(hi - 2 * s, hi - s, hi, array);
1051 mid = med3(lo, mid, hi, array);
1056 // Pull the median element out of the fray, and use it as a pivot.
1057 swap(from, mid, array);
1059 c = d = from + count - 1;
1061 // Repeatedly move b and c to each other, swapping elements so
1062 // that all elements before index b are less than the pivot, and all
1063 // elements after index c are greater than the pivot. a and b track
1064 // the elements equal to the pivot.
1067 while (b <= c && (comp = array[b] - array[from]) <= 0)
1076 while (c >= b && (comp = array[c] - array[from]) >= 0)
1092 // Swap pivot(s) back in place, the recurse on left and right sections.
1095 span = Math.min(a - from, b - a);
1096 vecswap(from, b - span, span, array);
1098 span = Math.min(d - c, hi - d - 1);
1099 vecswap(b, hi - span, span, array);
1103 qsort(array, from, span);
1107 qsort(array, hi - span, span);
1111 * Performs a stable sort on the elements, arranging them according to their
1114 * @param a the char array to sort
1116 public static void sort(char[] a)
1118 qsort(a, 0, a.length);
1122 * Performs a stable sort on the elements, arranging them according to their
1125 * @param a the char array to sort
1126 * @param fromIndex the first index to sort (inclusive)
1127 * @param toIndex the last index to sort (exclusive)
1128 * @throws IllegalArgumentException if fromIndex > toIndex
1129 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
1130 * || toIndex > a.length
1132 public static void sort(char[] a, int fromIndex, int toIndex)
1134 if (fromIndex > toIndex)
1135 throw new IllegalArgumentException();
1137 throw new ArrayIndexOutOfBoundsException();
1138 qsort(a, fromIndex, toIndex - fromIndex);
1142 * Finds the index of the median of three array elements.
1144 * @param a the first index
1145 * @param b the second index
1146 * @param c the third index
1147 * @param d the array
1148 * @return the index (a, b, or c) which has the middle value of the three
1150 private static int med3(int a, int b, int c, char[] d)
1153 ? (d[b] < d[c] ? b : d[a] < d[c] ? c : a)
1154 : (d[b] > d[c] ? b : d[a] > d[c] ? c : a));
1158 * Swaps the elements at two locations of an array
1160 * @param i the first index
1161 * @param j the second index
1162 * @param a the array
1164 private static void swap(int i, int j, char[] a)
1172 * Swaps two ranges of an array.
1174 * @param i the first range start
1175 * @param j the second range start
1176 * @param n the element count
1177 * @param a the array
1179 private static void vecswap(int i, int j, int n, char[] a)
1181 for ( ; n > 0; i++, j++, n--)
1186 * Performs a recursive modified quicksort.
1188 * @param array the array to sort
1189 * @param from the start index (inclusive)
1190 * @param count the number of elements to sort
1192 private static void qsort(char[] array, int from, int count)
1194 // Use an insertion sort on small arrays.
1197 for (int i = from + 1; i < from + count; i++)
1198 for (int j = i; j > from && array[j - 1] > array[j]; j--)
1199 swap(j, j - 1, array);
1203 // Determine a good median element.
1204 int mid = count / 2;
1206 int hi = from + count - 1;
1209 { // big arrays, pseudomedian of 9
1211 lo = med3(lo, lo + s, lo + 2 * s, array);
1212 mid = med3(mid - s, mid, mid + s, array);
1213 hi = med3(hi - 2 * s, hi - s, hi, array);
1215 mid = med3(lo, mid, hi, array);
1220 // Pull the median element out of the fray, and use it as a pivot.
1221 swap(from, mid, array);
1223 c = d = from + count - 1;
1225 // Repeatedly move b and c to each other, swapping elements so
1226 // that all elements before index b are less than the pivot, and all
1227 // elements after index c are greater than the pivot. a and b track
1228 // the elements equal to the pivot.
1231 while (b <= c && (comp = array[b] - array[from]) <= 0)
1240 while (c >= b && (comp = array[c] - array[from]) >= 0)
1256 // Swap pivot(s) back in place, the recurse on left and right sections.
1259 span = Math.min(a - from, b - a);
1260 vecswap(from, b - span, span, array);
1262 span = Math.min(d - c, hi - d - 1);
1263 vecswap(b, hi - span, span, array);
1267 qsort(array, from, span);
1271 qsort(array, hi - span, span);
1275 * Performs a stable sort on the elements, arranging them according to their
1278 * @param a the short array to sort
1280 public static void sort(short[] a)
1282 qsort(a, 0, a.length);
1286 * Performs a stable sort on the elements, arranging them according to their
1289 * @param a the short array to sort
1290 * @param fromIndex the first index to sort (inclusive)
1291 * @param toIndex the last index to sort (exclusive)
1292 * @throws IllegalArgumentException if fromIndex > toIndex
1293 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
1294 * || toIndex > a.length
1296 public static void sort(short[] a, int fromIndex, int toIndex)
1298 if (fromIndex > toIndex)
1299 throw new IllegalArgumentException();
1301 throw new ArrayIndexOutOfBoundsException();
1302 qsort(a, fromIndex, toIndex - fromIndex);
1306 * Finds the index of the median of three array elements.
1308 * @param a the first index
1309 * @param b the second index
1310 * @param c the third index
1311 * @param d the array
1312 * @return the index (a, b, or c) which has the middle value of the three
1314 private static int med3(int a, int b, int c, short[] d)
1317 ? (d[b] < d[c] ? b : d[a] < d[c] ? c : a)
1318 : (d[b] > d[c] ? b : d[a] > d[c] ? c : a));
1322 * Swaps the elements at two locations of an array
1324 * @param i the first index
1325 * @param j the second index
1326 * @param a the array
1328 private static void swap(int i, int j, short[] a)
1336 * Swaps two ranges of an array.
1338 * @param i the first range start
1339 * @param j the second range start
1340 * @param n the element count
1341 * @param a the array
1343 private static void vecswap(int i, int j, int n, short[] a)
1345 for ( ; n > 0; i++, j++, n--)
1350 * Performs a recursive modified quicksort.
1352 * @param array the array to sort
1353 * @param from the start index (inclusive)
1354 * @param count the number of elements to sort
1356 private static void qsort(short[] array, int from, int count)
1358 // Use an insertion sort on small arrays.
1361 for (int i = from + 1; i < from + count; i++)
1362 for (int j = i; j > from && array[j - 1] > array[j]; j--)
1363 swap(j, j - 1, array);
1367 // Determine a good median element.
1368 int mid = count / 2;
1370 int hi = from + count - 1;
1373 { // big arrays, pseudomedian of 9
1375 lo = med3(lo, lo + s, lo + 2 * s, array);
1376 mid = med3(mid - s, mid, mid + s, array);
1377 hi = med3(hi - 2 * s, hi - s, hi, array);
1379 mid = med3(lo, mid, hi, array);
1384 // Pull the median element out of the fray, and use it as a pivot.
1385 swap(from, mid, array);
1387 c = d = from + count - 1;
1389 // Repeatedly move b and c to each other, swapping elements so
1390 // that all elements before index b are less than the pivot, and all
1391 // elements after index c are greater than the pivot. a and b track
1392 // the elements equal to the pivot.
1395 while (b <= c && (comp = array[b] - array[from]) <= 0)
1404 while (c >= b && (comp = array[c] - array[from]) >= 0)
1420 // Swap pivot(s) back in place, the recurse on left and right sections.
1423 span = Math.min(a - from, b - a);
1424 vecswap(from, b - span, span, array);
1426 span = Math.min(d - c, hi - d - 1);
1427 vecswap(b, hi - span, span, array);
1431 qsort(array, from, span);
1435 qsort(array, hi - span, span);
1439 * Performs a stable sort on the elements, arranging them according to their
1442 * @param a the int array to sort
1444 public static void sort(int[] a)
1446 qsort(a, 0, a.length);
1450 * Performs a stable sort on the elements, arranging them according to their
1453 * @param a the int array to sort
1454 * @param fromIndex the first index to sort (inclusive)
1455 * @param toIndex the last index to sort (exclusive)
1456 * @throws IllegalArgumentException if fromIndex > toIndex
1457 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
1458 * || toIndex > a.length
1460 public static void sort(int[] a, int fromIndex, int toIndex)
1462 if (fromIndex > toIndex)
1463 throw new IllegalArgumentException();
1465 throw new ArrayIndexOutOfBoundsException();
1466 qsort(a, fromIndex, toIndex - fromIndex);
1470 * Finds the index of the median of three array elements.
1472 * @param a the first index
1473 * @param b the second index
1474 * @param c the third index
1475 * @param d the array
1476 * @return the index (a, b, or c) which has the middle value of the three
1478 private static int med3(int a, int b, int c, int[] d)
1481 ? (d[b] < d[c] ? b : d[a] < d[c] ? c : a)
1482 : (d[b] > d[c] ? b : d[a] > d[c] ? c : a));
1486 * Swaps the elements at two locations of an array
1488 * @param i the first index
1489 * @param j the second index
1490 * @param a the array
1492 private static void swap(int i, int j, int[] a)
1500 * Swaps two ranges of an array.
1502 * @param i the first range start
1503 * @param j the second range start
1504 * @param n the element count
1505 * @param a the array
1507 private static void vecswap(int i, int j, int n, int[] a)
1509 for ( ; n > 0; i++, j++, n--)
1514 * Compares two integers in natural order, since a - b is inadequate.
1516 * @param a the first int
1517 * @param b the second int
1518 * @return < 0, 0, or > 0 accorting to the comparison
1520 private static int compare(int a, int b)
1522 return a < b ? -1 : a == b ? 0 : 1;
1526 * Performs a recursive modified quicksort.
1528 * @param array the array to sort
1529 * @param from the start index (inclusive)
1530 * @param count the number of elements to sort
1532 private static void qsort(int[] array, int from, int count)
1534 // Use an insertion sort on small arrays.
1537 for (int i = from + 1; i < from + count; i++)
1538 for (int j = i; j > from && array[j - 1] > array[j]; j--)
1539 swap(j, j - 1, array);
1543 // Determine a good median element.
1544 int mid = count / 2;
1546 int hi = from + count - 1;
1549 { // big arrays, pseudomedian of 9
1551 lo = med3(lo, lo + s, lo + 2 * s, array);
1552 mid = med3(mid - s, mid, mid + s, array);
1553 hi = med3(hi - 2 * s, hi - s, hi, array);
1555 mid = med3(lo, mid, hi, array);
1560 // Pull the median element out of the fray, and use it as a pivot.
1561 swap(from, mid, array);
1563 c = d = from + count - 1;
1565 // Repeatedly move b and c to each other, swapping elements so
1566 // that all elements before index b are less than the pivot, and all
1567 // elements after index c are greater than the pivot. a and b track
1568 // the elements equal to the pivot.
1571 while (b <= c && (comp = compare(array[b], array[from])) <= 0)
1580 while (c >= b && (comp = compare(array[c], array[from])) >= 0)
1596 // Swap pivot(s) back in place, the recurse on left and right sections.
1599 span = Math.min(a - from, b - a);
1600 vecswap(from, b - span, span, array);
1602 span = Math.min(d - c, hi - d - 1);
1603 vecswap(b, hi - span, span, array);
1607 qsort(array, from, span);
1611 qsort(array, hi - span, span);
1615 * Performs a stable sort on the elements, arranging them according to their
1618 * @param a the long array to sort
1620 public static void sort(long[] a)
1622 qsort(a, 0, a.length);
1626 * Performs a stable sort on the elements, arranging them according to their
1629 * @param a the long array to sort
1630 * @param fromIndex the first index to sort (inclusive)
1631 * @param toIndex the last index to sort (exclusive)
1632 * @throws IllegalArgumentException if fromIndex > toIndex
1633 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
1634 * || toIndex > a.length
1636 public static void sort(long[] a, int fromIndex, int toIndex)
1638 if (fromIndex > toIndex)
1639 throw new IllegalArgumentException();
1641 throw new ArrayIndexOutOfBoundsException();
1642 qsort(a, fromIndex, toIndex - fromIndex);
1646 * Finds the index of the median of three array elements.
1648 * @param a the first index
1649 * @param b the second index
1650 * @param c the third index
1651 * @param d the array
1652 * @return the index (a, b, or c) which has the middle value of the three
1654 private static int med3(int a, int b, int c, long[] d)
1657 ? (d[b] < d[c] ? b : d[a] < d[c] ? c : a)
1658 : (d[b] > d[c] ? b : d[a] > d[c] ? c : a));
1662 * Swaps the elements at two locations of an array
1664 * @param i the first index
1665 * @param j the second index
1666 * @param a the array
1668 private static void swap(int i, int j, long[] a)
1676 * Swaps two ranges of an array.
1678 * @param i the first range start
1679 * @param j the second range start
1680 * @param n the element count
1681 * @param a the array
1683 private static void vecswap(int i, int j, int n, long[] a)
1685 for ( ; n > 0; i++, j++, n--)
1690 * Compares two longs in natural order, since a - b is inadequate.
1692 * @param a the first long
1693 * @param b the second long
1694 * @return < 0, 0, or > 0 accorting to the comparison
1696 private static int compare(long a, long b)
1698 return a < b ? -1 : a == b ? 0 : 1;
1702 * Performs a recursive modified quicksort.
1704 * @param array the array to sort
1705 * @param from the start index (inclusive)
1706 * @param count the number of elements to sort
1708 private static void qsort(long[] array, int from, int count)
1710 // Use an insertion sort on small arrays.
1713 for (int i = from + 1; i < from + count; i++)
1714 for (int j = i; j > from && array[j - 1] > array[j]; j--)
1715 swap(j, j - 1, array);
1719 // Determine a good median element.
1720 int mid = count / 2;
1722 int hi = from + count - 1;
1725 { // big arrays, pseudomedian of 9
1727 lo = med3(lo, lo + s, lo + 2 * s, array);
1728 mid = med3(mid - s, mid, mid + s, array);
1729 hi = med3(hi - 2 * s, hi - s, hi, array);
1731 mid = med3(lo, mid, hi, array);
1736 // Pull the median element out of the fray, and use it as a pivot.
1737 swap(from, mid, array);
1739 c = d = from + count - 1;
1741 // Repeatedly move b and c to each other, swapping elements so
1742 // that all elements before index b are less than the pivot, and all
1743 // elements after index c are greater than the pivot. a and b track
1744 // the elements equal to the pivot.
1747 while (b <= c && (comp = compare(array[b], array[from])) <= 0)
1756 while (c >= b && (comp = compare(array[c], array[from])) >= 0)
1772 // Swap pivot(s) back in place, the recurse on left and right sections.
1775 span = Math.min(a - from, b - a);
1776 vecswap(from, b - span, span, array);
1778 span = Math.min(d - c, hi - d - 1);
1779 vecswap(b, hi - span, span, array);
1783 qsort(array, from, span);
1787 qsort(array, hi - span, span);
1791 * Performs a stable sort on the elements, arranging them according to their
1794 * @param a the float array to sort
1796 public static void sort(float[] a)
1798 qsort(a, 0, a.length);
1802 * Performs a stable sort on the elements, arranging them according to their
1805 * @param a the float array to sort
1806 * @param fromIndex the first index to sort (inclusive)
1807 * @param toIndex the last index to sort (exclusive)
1808 * @throws IllegalArgumentException if fromIndex > toIndex
1809 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
1810 * || toIndex > a.length
1812 public static void sort(float[] a, int fromIndex, int toIndex)
1814 if (fromIndex > toIndex)
1815 throw new IllegalArgumentException();
1817 throw new ArrayIndexOutOfBoundsException();
1818 qsort(a, fromIndex, toIndex - fromIndex);
1822 * Finds the index of the median of three array elements.
1824 * @param a the first index
1825 * @param b the second index
1826 * @param c the third index
1827 * @param d the array
1828 * @return the index (a, b, or c) which has the middle value of the three
1830 private static int med3(int a, int b, int c, float[] d)
1832 return (Float.compare(d[a], d[b]) < 0
1833 ? (Float.compare(d[b], d[c]) < 0 ? b
1834 : Float.compare(d[a], d[c]) < 0 ? c : a)
1835 : (Float.compare(d[b], d[c]) > 0 ? b
1836 : Float.compare(d[a], d[c]) > 0 ? c : a));
1840 * Swaps the elements at two locations of an array
1842 * @param i the first index
1843 * @param j the second index
1844 * @param a the array
1846 private static void swap(int i, int j, float[] a)
1854 * Swaps two ranges of an array.
1856 * @param i the first range start
1857 * @param j the second range start
1858 * @param n the element count
1859 * @param a the array
1861 private static void vecswap(int i, int j, int n, float[] a)
1863 for ( ; n > 0; i++, j++, n--)
1868 * Performs a recursive modified quicksort.
1870 * @param array the array to sort
1871 * @param from the start index (inclusive)
1872 * @param count the number of elements to sort
1874 private static void qsort(float[] array, int from, int count)
1876 // Use an insertion sort on small arrays.
1879 for (int i = from + 1; i < from + count; i++)
1881 j > from && Float.compare(array[j - 1], array[j]) > 0;
1884 swap(j, j - 1, array);
1889 // Determine a good median element.
1890 int mid = count / 2;
1892 int hi = from + count - 1;
1895 { // big arrays, pseudomedian of 9
1897 lo = med3(lo, lo + s, lo + 2 * s, array);
1898 mid = med3(mid - s, mid, mid + s, array);
1899 hi = med3(hi - 2 * s, hi - s, hi, array);
1901 mid = med3(lo, mid, hi, array);
1906 // Pull the median element out of the fray, and use it as a pivot.
1907 swap(from, mid, array);
1909 c = d = from + count - 1;
1911 // Repeatedly move b and c to each other, swapping elements so
1912 // that all elements before index b are less than the pivot, and all
1913 // elements after index c are greater than the pivot. a and b track
1914 // the elements equal to the pivot.
1917 while (b <= c && (comp = Float.compare(array[b], array[from])) <= 0)
1926 while (c >= b && (comp = Float.compare(array[c], array[from])) >= 0)
1942 // Swap pivot(s) back in place, the recurse on left and right sections.
1945 span = Math.min(a - from, b - a);
1946 vecswap(from, b - span, span, array);
1948 span = Math.min(d - c, hi - d - 1);
1949 vecswap(b, hi - span, span, array);
1953 qsort(array, from, span);
1957 qsort(array, hi - span, span);
1961 * Performs a stable sort on the elements, arranging them according to their
1964 * @param a the double array to sort
1966 public static void sort(double[] a)
1968 qsort(a, 0, a.length);
1972 * Performs a stable sort on the elements, arranging them according to their
1975 * @param a the double array to sort
1976 * @param fromIndex the first index to sort (inclusive)
1977 * @param toIndex the last index to sort (exclusive)
1978 * @throws IllegalArgumentException if fromIndex > toIndex
1979 * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
1980 * || toIndex > a.length
1982 public static void sort(double[] a, int fromIndex, int toIndex)
1984 if (fromIndex > toIndex)
1985 throw new IllegalArgumentException();
1987 throw new ArrayIndexOutOfBoundsException();
1988 qsort(a, fromIndex, toIndex - fromIndex);
1992 * Finds the index of the median of three array elements.
1994 * @param a the first index
1995 * @param b the second index
1996 * @param c the third index
1997 * @param d the array
1998 * @return the index (a, b, or c) which has the middle value of the three
2000 private static int med3(int a, int b, int c, double[] d)
2002 return (Double.compare(d[a], d[b]) < 0
2003 ? (Double.compare(d[b], d[c]) < 0 ? b
2004 : Double.compare(d[a], d[c]) < 0 ? c : a)
2005 : (Double.compare(d[b], d[c]) > 0 ? b
2006 : Double.compare(d[a], d[c]) > 0 ? c : a));
2010 * Swaps the elements at two locations of an array
2012 * @param i the first index
2013 * @param j the second index
2014 * @param a the array
2016 private static void swap(int i, int j, double[] a)
2024 * Swaps two ranges of an array.
2026 * @param i the first range start
2027 * @param j the second range start
2028 * @param n the element count
2029 * @param a the array
2031 private static void vecswap(int i, int j, int n, double[] a)
2033 for ( ; n > 0; i++, j++, n--)
2038 * Performs a recursive modified quicksort.
2040 * @param array the array to sort
2041 * @param from the start index (inclusive)
2042 * @param count the number of elements to sort
2044 private static void qsort(double[] array, int from, int count)
2046 // Use an insertion sort on small arrays.
2049 for (int i = from + 1; i < from + count; i++)
2051 j > from && Double.compare(array[j - 1], array[j]) > 0;
2054 swap(j, j - 1, array);
2059 // Determine a good median element.
2060 int mid = count / 2;
2062 int hi = from + count - 1;
2065 { // big arrays, pseudomedian of 9
2067 lo = med3(lo, lo + s, lo + 2 * s, array);
2068 mid = med3(mid - s, mid, mid + s, array);
2069 hi = med3(hi - 2 * s, hi - s, hi, array);
2071 mid = med3(lo, mid, hi, array);
2076 // Pull the median element out of the fray, and use it as a pivot.
2077 swap(from, mid, array);
2079 c = d = from + count - 1;
2081 // Repeatedly move b and c to each other, swapping elements so
2082 // that all elements before index b are less than the pivot, and all
2083 // elements after index c are greater than the pivot. a and b track
2084 // the elements equal to the pivot.
2087 while (b <= c && (comp = Double.compare(array[b], array[from])) <= 0)
2096 while (c >= b && (comp = Double.compare(array[c], array[from])) >= 0)
2112 // Swap pivot(s) back in place, the recurse on left and right sections.
2115 span = Math.min(a - from, b - a);
2116 vecswap(from, b - span, span, array);
2118 span = Math.min(d - c, hi - d - 1);
2119 vecswap(b, hi - span, span, array);
2123 qsort(array, from, span);
2127 qsort(array, hi - span, span);
2131 * Sort an array of Objects according to their natural ordering. The sort is
2132 * guaranteed to be stable, that is, equal elements will not be reordered.
2133 * The sort algorithm is a mergesort with the merge omitted if the last
2134 * element of one half comes before the first element of the other half. This
2135 * algorithm gives guaranteed O(n*log(n)) time, at the expense of making a
2136 * copy of the array.
2138 * @param a the array to be sorted
2139 * @throws ClassCastException if any two elements are not mutually
2141 * @throws NullPointerException if an element is null (since
2142 * null.compareTo cannot work)
2145 public static void sort(Object[] a)
2147 sort(a, 0, a.length, null);
2151 * Sort an array of Objects according to a Comparator. The sort is
2152 * guaranteed to be stable, that is, equal elements will not be reordered.
2153 * The sort algorithm is a mergesort with the merge omitted if the last
2154 * element of one half comes before the first element of the other half. This
2155 * algorithm gives guaranteed O(n*log(n)) time, at the expense of making a
2156 * copy of the array.
2158 * @param a the array to be sorted
2159 * @param c a Comparator to use in sorting the array; or null to indicate
2160 * the elements' natural order
2161 * @throws ClassCastException if any two elements are not mutually
2162 * comparable by the Comparator provided
2163 * @throws NullPointerException if a null element is compared with natural
2164 * ordering (only possible when c is null)
2166 public static <T> void sort(T[] a, Comparator<? super T> c)
2168 sort(a, 0, a.length, c);
2172 * Sort an array of Objects according to their natural ordering. The sort is
2173 * guaranteed to be stable, that is, equal elements will not be reordered.
2174 * The sort algorithm is a mergesort with the merge omitted if the last
2175 * element of one half comes before the first element of the other half. This
2176 * algorithm gives guaranteed O(n*log(n)) time, at the expense of making a
2177 * copy of the array.
2179 * @param a the array to be sorted
2180 * @param fromIndex the index of the first element to be sorted
2181 * @param toIndex the index of the last element to be sorted plus one
2182 * @throws ClassCastException if any two elements are not mutually
2184 * @throws NullPointerException if an element is null (since
2185 * null.compareTo cannot work)
2186 * @throws ArrayIndexOutOfBoundsException if fromIndex and toIndex
2188 * @throws IllegalArgumentException if fromIndex > toIndex
2190 public static void sort(Object[] a, int fromIndex, int toIndex)
2192 sort(a, fromIndex, toIndex, null);
2196 * Sort an array of Objects according to a Comparator. The sort is
2197 * guaranteed to be stable, that is, equal elements will not be reordered.
2198 * The sort algorithm is a mergesort with the merge omitted if the last
2199 * element of one half comes before the first element of the other half. This
2200 * algorithm gives guaranteed O(n*log(n)) time, at the expense of making a
2201 * copy of the array.
2203 * @param a the array to be sorted
2204 * @param fromIndex the index of the first element to be sorted
2205 * @param toIndex the index of the last element to be sorted plus one
2206 * @param c a Comparator to use in sorting the array; or null to indicate
2207 * the elements' natural order
2208 * @throws ClassCastException if any two elements are not mutually
2209 * comparable by the Comparator provided
2210 * @throws ArrayIndexOutOfBoundsException if fromIndex and toIndex
2212 * @throws IllegalArgumentException if fromIndex > toIndex
2213 * @throws NullPointerException if a null element is compared with natural
2214 * ordering (only possible when c is null)
2216 public static <T> void sort(T[] a, int fromIndex, int toIndex,
2217 Comparator<? super T> c)
2219 if (fromIndex > toIndex)
2220 throw new IllegalArgumentException("fromIndex " + fromIndex
2221 + " > toIndex " + toIndex);
2223 throw new ArrayIndexOutOfBoundsException();
2225 // In general, the code attempts to be simple rather than fast, the
2226 // idea being that a good optimising JIT will be able to optimise it
2227 // better than I can, and if I try it will make it more confusing for
2228 // the JIT. First presort the array in chunks of length 6 with insertion
2229 // sort. A mergesort would give too much overhead for this length.
2230 for (int chunk = fromIndex; chunk < toIndex; chunk += 6)
2232 int end = Math.min(chunk + 6, toIndex);
2233 for (int i = chunk + 1; i < end; i++)
2235 if (Collections.compare(a[i - 1], a[i], c) > 0)
2237 // not already sorted
2246 && Collections.compare(a[j - 1], elem, c) > 0);
2252 int len = toIndex - fromIndex;
2253 // If length is smaller or equal 6 we are done.
2258 T[] dest = (T[]) new Object[len];
2259 T[] t = null; // t is used for swapping src and dest
2261 // The difference of the fromIndex of the src and dest array.
2262 int srcDestDiff = -fromIndex;
2264 // The merges are done in this loop
2265 for (int size = 6; size < len; size <<= 1)
2267 for (int start = fromIndex; start < toIndex; start += size << 1)
2269 // mid is the start of the second sublist;
2270 // end the start of the next sublist (or end of array).
2271 int mid = start + size;
2272 int end = Math.min(toIndex, mid + size);
2274 // The second list is empty or the elements are already in
2275 // order - no need to merge
2277 || Collections.compare(src[mid - 1], src[mid], c) <= 0)
2279 System.arraycopy(src, start,
2280 dest, start + srcDestDiff, end - start);
2282 // The two halves just need swapping - no need to merge
2284 else if (Collections.compare(src[start], src[end - 1], c) > 0)
2286 System.arraycopy(src, start,
2287 dest, end - size + srcDestDiff, size);
2288 System.arraycopy(src, mid,
2289 dest, start + srcDestDiff, end - mid);
2294 // Declare a lot of variables to save repeating
2295 // calculations. Hopefully a decent JIT will put these
2296 // in registers and make this fast
2299 int i = start + srcDestDiff;
2301 // The main merge loop; terminates as soon as either
2303 while (p1 < mid && p2 < end)
2306 src[(Collections.compare(src[p1], src[p2], c) <= 0
2310 // Finish up by copying the remainder of whichever half
2313 System.arraycopy(src, p1, dest, i, mid - p1);
2315 System.arraycopy(src, p2, dest, i, end - p2);
2318 // swap src and dest ready for the next merge
2322 fromIndex += srcDestDiff;
2323 toIndex += srcDestDiff;
2324 srcDestDiff = -srcDestDiff;
2327 // make sure the result ends up back in the right place. Note
2328 // that src and dest may have been swapped above, so src
2329 // contains the sorted array.
2332 // Note that fromIndex == 0.
2333 System.arraycopy(src, 0, a, srcDestDiff, toIndex);
2338 * Returns a list "view" of the specified array. This method is intended to
2339 * make it easy to use the Collections API with existing array-based APIs and
2340 * programs. Changes in the list or the array show up in both places. The
2341 * list does not support element addition or removal, but does permit
2342 * value modification. The returned list implements both Serializable and
2345 * @param a the array to return a view of (<code>null</code> not permitted)
2346 * @return a fixed-size list, changes to which "write through" to the array
2348 * @throws NullPointerException if <code>a</code> is <code>null</code>.
2351 * @see Arrays.ArrayList
2353 public static <T> List<T> asList(final T... a)
2355 return new Arrays.ArrayList(a);
2359 * Returns the hashcode of an array of long numbers. If two arrays
2360 * are equal, according to <code>equals()</code>, they should have the
2361 * same hashcode. The hashcode returned by the method is equal to that
2362 * obtained by the corresponding <code>List</code> object. This has the same
2363 * data, but represents longs in their wrapper class, <code>Long</code>.
2364 * For <code>null</code>, 0 is returned.
2366 * @param v an array of long numbers for which the hash code should be
2368 * @return the hash code of the array, or 0 if null was given.
2371 public static int hashCode(long[] v)
2376 for (int i = 0; i < v.length; ++i)
2378 int elt = (int) (v[i] ^ (v[i] >>> 32));
2379 result = 31 * result + elt;
2385 * Returns the hashcode of an array of integer numbers. If two arrays
2386 * are equal, according to <code>equals()</code>, they should have the
2387 * same hashcode. The hashcode returned by the method is equal to that
2388 * obtained by the corresponding <code>List</code> object. This has the same
2389 * data, but represents ints in their wrapper class, <code>Integer</code>.
2390 * For <code>null</code>, 0 is returned.
2392 * @param v an array of integer numbers for which the hash code should be
2394 * @return the hash code of the array, or 0 if null was given.
2397 public static int hashCode(int[] v)
2402 for (int i = 0; i < v.length; ++i)
2403 result = 31 * result + v[i];
2408 * Returns the hashcode of an array of short numbers. If two arrays
2409 * are equal, according to <code>equals()</code>, they should have the
2410 * same hashcode. The hashcode returned by the method is equal to that
2411 * obtained by the corresponding <code>List</code> object. This has the same
2412 * data, but represents shorts in their wrapper class, <code>Short</code>.
2413 * For <code>null</code>, 0 is returned.
2415 * @param v an array of short numbers for which the hash code should be
2417 * @return the hash code of the array, or 0 if null was given.
2420 public static int hashCode(short[] v)
2425 for (int i = 0; i < v.length; ++i)
2426 result = 31 * result + v[i];
2431 * Returns the hashcode of an array of characters. If two arrays
2432 * are equal, according to <code>equals()</code>, they should have the
2433 * same hashcode. The hashcode returned by the method is equal to that
2434 * obtained by the corresponding <code>List</code> object. This has the same
2435 * data, but represents chars in their wrapper class, <code>Character</code>.
2436 * For <code>null</code>, 0 is returned.
2438 * @param v an array of characters for which the hash code should be
2440 * @return the hash code of the array, or 0 if null was given.
2443 public static int hashCode(char[] v)
2448 for (int i = 0; i < v.length; ++i)
2449 result = 31 * result + v[i];
2454 * Returns the hashcode of an array of bytes. If two arrays
2455 * are equal, according to <code>equals()</code>, they should have the
2456 * same hashcode. The hashcode returned by the method is equal to that
2457 * obtained by the corresponding <code>List</code> object. This has the same
2458 * data, but represents bytes in their wrapper class, <code>Byte</code>.
2459 * For <code>null</code>, 0 is returned.
2461 * @param v an array of bytes for which the hash code should be
2463 * @return the hash code of the array, or 0 if null was given.
2466 public static int hashCode(byte[] v)
2471 for (int i = 0; i < v.length; ++i)
2472 result = 31 * result + v[i];
2477 * Returns the hashcode of an array of booleans. If two arrays
2478 * are equal, according to <code>equals()</code>, they should have the
2479 * same hashcode. The hashcode returned by the method is equal to that
2480 * obtained by the corresponding <code>List</code> object. This has the same
2481 * data, but represents booleans in their wrapper class,
2482 * <code>Boolean</code>. For <code>null</code>, 0 is returned.
2484 * @param v an array of booleans for which the hash code should be
2486 * @return the hash code of the array, or 0 if null was given.
2489 public static int hashCode(boolean[] v)
2494 for (int i = 0; i < v.length; ++i)
2495 result = 31 * result + (v[i] ? 1231 : 1237);
2500 * Returns the hashcode of an array of floats. If two arrays
2501 * are equal, according to <code>equals()</code>, they should have the
2502 * same hashcode. The hashcode returned by the method is equal to that
2503 * obtained by the corresponding <code>List</code> object. This has the same
2504 * data, but represents floats in their wrapper class, <code>Float</code>.
2505 * For <code>null</code>, 0 is returned.
2507 * @param v an array of floats for which the hash code should be
2509 * @return the hash code of the array, or 0 if null was given.
2512 public static int hashCode(float[] v)
2517 for (int i = 0; i < v.length; ++i)
2518 result = 31 * result + Float.floatToIntBits(v[i]);
2523 * Returns the hashcode of an array of doubles. If two arrays
2524 * are equal, according to <code>equals()</code>, they should have the
2525 * same hashcode. The hashcode returned by the method is equal to that
2526 * obtained by the corresponding <code>List</code> object. This has the same
2527 * data, but represents doubles in their wrapper class, <code>Double</code>.
2528 * For <code>null</code>, 0 is returned.
2530 * @param v an array of doubles for which the hash code should be
2532 * @return the hash code of the array, or 0 if null was given.
2535 public static int hashCode(double[] v)
2540 for (int i = 0; i < v.length; ++i)
2542 long l = Double.doubleToLongBits(v[i]);
2543 int elt = (int) (l ^ (l >>> 32));
2544 result = 31 * result + elt;
2550 * Returns the hashcode of an array of objects. If two arrays
2551 * are equal, according to <code>equals()</code>, they should have the
2552 * same hashcode. The hashcode returned by the method is equal to that
2553 * obtained by the corresponding <code>List</code> object.
2554 * For <code>null</code>, 0 is returned.
2556 * @param v an array of integer numbers for which the hash code should be
2558 * @return the hash code of the array, or 0 if null was given.
2561 public static int hashCode(Object[] v)
2566 for (int i = 0; i < v.length; ++i)
2568 int elt = v[i] == null ? 0 : v[i].hashCode();
2569 result = 31 * result + elt;
2574 public static int deepHashCode(Object[] v)
2579 for (int i = 0; i < v.length; ++i)
2584 else if (v[i] instanceof boolean[])
2585 elt = hashCode((boolean[]) v[i]);
2586 else if (v[i] instanceof byte[])
2587 elt = hashCode((byte[]) v[i]);
2588 else if (v[i] instanceof char[])
2589 elt = hashCode((char[]) v[i]);
2590 else if (v[i] instanceof short[])
2591 elt = hashCode((short[]) v[i]);
2592 else if (v[i] instanceof int[])
2593 elt = hashCode((int[]) v[i]);
2594 else if (v[i] instanceof long[])
2595 elt = hashCode((long[]) v[i]);
2596 else if (v[i] instanceof float[])
2597 elt = hashCode((float[]) v[i]);
2598 else if (v[i] instanceof double[])
2599 elt = hashCode((double[]) v[i]);
2600 else if (v[i] instanceof Object[])
2601 elt = hashCode((Object[]) v[i]);
2603 elt = v[i].hashCode();
2604 result = 31 * result + elt;
2610 public static boolean deepEquals(Object[] v1, Object[] v2)
2614 if (v2 == null || v1.length != v2.length)
2617 for (int i = 0; i < v1.length; ++i)
2624 if (e1 == null || e2 == null)
2628 if (e1 instanceof boolean[] && e2 instanceof boolean[])
2629 check = equals((boolean[]) e1, (boolean[]) e2);
2630 else if (e1 instanceof byte[] && e2 instanceof byte[])
2631 check = equals((byte[]) e1, (byte[]) e2);
2632 else if (e1 instanceof char[] && e2 instanceof char[])
2633 check = equals((char[]) e1, (char[]) e2);
2634 else if (e1 instanceof short[] && e2 instanceof short[])
2635 check = equals((short[]) e1, (short[]) e2);
2636 else if (e1 instanceof int[] && e2 instanceof int[])
2637 check = equals((int[]) e1, (int[]) e2);
2638 else if (e1 instanceof long[] && e2 instanceof long[])
2639 check = equals((long[]) e1, (long[]) e2);
2640 else if (e1 instanceof float[] && e2 instanceof float[])
2641 check = equals((float[]) e1, (float[]) e2);
2642 else if (e1 instanceof double[] && e2 instanceof double[])
2643 check = equals((double[]) e1, (double[]) e2);
2644 else if (e1 instanceof Object[] && e2 instanceof Object[])
2645 check = equals((Object[]) e1, (Object[]) e2);
2647 check = e1.equals(e2);
2656 * Returns a String representation of the argument array. Returns "null"
2657 * if <code>a</code> is null.
2658 * @param v the array to represent
2659 * @return a String representing this array
2662 public static String toString(boolean[] v)
2666 StringBuilder b = new StringBuilder("[");
2667 for (int i = 0; i < v.length; ++i)
2674 return b.toString();
2678 * Returns a String representation of the argument array. Returns "null"
2679 * if <code>a</code> is null.
2680 * @param v the array to represent
2681 * @return a String representing this array
2684 public static String toString(byte[] v)
2688 StringBuilder b = new StringBuilder("[");
2689 for (int i = 0; i < v.length; ++i)
2696 return b.toString();
2700 * Returns a String representation of the argument array. Returns "null"
2701 * if <code>a</code> is null.
2702 * @param v the array to represent
2703 * @return a String representing this array
2706 public static String toString(char[] v)
2710 StringBuilder b = new StringBuilder("[");
2711 for (int i = 0; i < v.length; ++i)
2718 return b.toString();
2722 * Returns a String representation of the argument array. Returns "null"
2723 * if <code>a</code> is null.
2724 * @param v the array to represent
2725 * @return a String representing this array
2728 public static String toString(short[] v)
2732 StringBuilder b = new StringBuilder("[");
2733 for (int i = 0; i < v.length; ++i)
2740 return b.toString();
2744 * Returns a String representation of the argument array. Returns "null"
2745 * if <code>a</code> is null.
2746 * @param v the array to represent
2747 * @return a String representing this array
2750 public static String toString(int[] v)
2754 StringBuilder b = new StringBuilder("[");
2755 for (int i = 0; i < v.length; ++i)
2762 return b.toString();
2766 * Returns a String representation of the argument array. Returns "null"
2767 * if <code>a</code> is null.
2768 * @param v the array to represent
2769 * @return a String representing this array
2772 public static String toString(long[] v)
2776 StringBuilder b = new StringBuilder("[");
2777 for (int i = 0; i < v.length; ++i)
2784 return b.toString();
2788 * Returns a String representation of the argument array. Returns "null"
2789 * if <code>a</code> is null.
2790 * @param v the array to represent
2791 * @return a String representing this array
2794 public static String toString(float[] v)
2798 StringBuilder b = new StringBuilder("[");
2799 for (int i = 0; i < v.length; ++i)
2806 return b.toString();
2810 * Returns a String representation of the argument array. Returns "null"
2811 * if <code>a</code> is null.
2812 * @param v the array to represent
2813 * @return a String representing this array
2816 public static String toString(double[] v)
2820 StringBuilder b = new StringBuilder("[");
2821 for (int i = 0; i < v.length; ++i)
2828 return b.toString();
2832 * Returns a String representation of the argument array. Returns "null"
2833 * if <code>a</code> is null.
2834 * @param v the array to represent
2835 * @return a String representing this array
2838 public static String toString(Object[] v)
2842 StringBuilder b = new StringBuilder("[");
2843 for (int i = 0; i < v.length; ++i)
2850 return b.toString();
2853 private static void deepToString(Object[] v, StringBuilder b, HashSet seen)
2856 for (int i = 0; i < v.length; ++i)
2863 else if (elt instanceof boolean[])
2864 b.append(toString((boolean[]) elt));
2865 else if (elt instanceof byte[])
2866 b.append(toString((byte[]) elt));
2867 else if (elt instanceof char[])
2868 b.append(toString((char[]) elt));
2869 else if (elt instanceof short[])
2870 b.append(toString((short[]) elt));
2871 else if (elt instanceof int[])
2872 b.append(toString((int[]) elt));
2873 else if (elt instanceof long[])
2874 b.append(toString((long[]) elt));
2875 else if (elt instanceof float[])
2876 b.append(toString((float[]) elt));
2877 else if (elt instanceof double[])
2878 b.append(toString((double[]) elt));
2879 else if (elt instanceof Object[])
2881 Object[] os = (Object[]) elt;
2882 if (seen.contains(os))
2887 deepToString(os, b, seen);
2897 public static String deepToString(Object[] v)
2901 HashSet seen = new HashSet();
2902 StringBuilder b = new StringBuilder();
2903 deepToString(v, b, seen);
2904 return b.toString();
2908 * Inner class used by {@link #asList(Object[])} to provide a list interface
2909 * to an array. The name, though it clashes with java.util.ArrayList, is
2910 * Sun's choice for Serialization purposes. Element addition and removal
2911 * is prohibited, but values can be modified.
2913 * @author Eric Blake (ebb9@email.byu.edu)
2914 * @status updated to 1.4
2916 private static final class ArrayList<E> extends AbstractList<E>
2917 implements Serializable, RandomAccess
2919 // We override the necessary methods, plus others which will be much
2920 // more efficient with direct iteration rather than relying on iterator().
2923 * Compatible with JDK 1.4.
2925 private static final long serialVersionUID = -2764017481108945198L;
2928 * The array we are viewing.
2931 private final E[] a;
2934 * Construct a list view of the array.
2935 * @param a the array to view
2936 * @throws NullPointerException if a is null
2940 // We have to explicitly check.
2942 throw new NullPointerException();
2947 * Returns the object at the specified index in
2950 * @param index The index to retrieve an object from.
2951 * @return The object at the array index specified.
2953 public E get(int index)
2959 * Returns the size of the array.
2969 * Replaces the object at the specified index
2970 * with the supplied element.
2972 * @param index The index at which to place the new object.
2973 * @param element The new object.
2974 * @return The object replaced by this operation.
2976 public E set(int index, E element)
2984 * Returns true if the array contains the
2987 * @param o The object to look for.
2988 * @return True if the object was found.
2990 public boolean contains(Object o)
2992 return lastIndexOf(o) >= 0;
2996 * Returns the first index at which the
2997 * object, o, occurs in the array.
2999 * @param o The object to search for.
3000 * @return The first relevant index.
3002 public int indexOf(Object o)
3004 int size = a.length;
3005 for (int i = 0; i < size; i++)
3006 if (ArrayList.equals(o, a[i]))
3012 * Returns the last index at which the
3013 * object, o, occurs in the array.
3015 * @param o The object to search for.
3016 * @return The last relevant index.
3018 public int lastIndexOf(Object o)
3022 if (ArrayList.equals(o, a[i]))
3028 * Transforms the list into an array of
3029 * objects, by simplying cloning the array
3030 * wrapped by this list.
3032 * @return A clone of the internal array.
3034 public Object[] toArray()
3036 return (Object[]) a.clone();
3040 * Copies the objects from this list into
3041 * the supplied array. The supplied array
3042 * is shrunk or enlarged to the size of the
3043 * internal array, and filled with its objects.
3045 * @param array The array to fill with the objects in this list.
3046 * @return The array containing the objects in this list,
3047 * which may or may not be == to array.
3049 public <T> T[] toArray(T[] array)
3051 int size = a.length;
3052 if (array.length < size)
3053 array = (T[]) Array.newInstance(array.getClass().getComponentType(),
3055 else if (array.length > size)
3058 System.arraycopy(a, 0, array, 0, size);