static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)
描述 (Description)
java.util.Arrays.(T[] a, int fromIndex, int toIndex, Comparator《? super T》 c)方法根据指定比较器引发的顺序对指定对象数组的指定范围进行排序。 要排序的范围从索引fromIndex(包括)延伸到index toIndex,exclusive。 (如果fromIndex == toIndex,则要排序的范围为空。)范围内的所有元素必须由指定的比较器相互比较(即,c.compare(e1,e2)不得为任何元素e1抛出ClassCastException。和范围内的e2)。
这种保证是稳定的:相同的元素不会因排序而重新排序。
排序算法是修改后的mergesort(如果低子列表中的最高元素小于高子列表中的最低元素,则省略合并)。 该算法提供有保证的n * log(n)性能。
声明 (Declaration)
以下是java.util.Arrays.sort()方法的声明
public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)
参数 (Parameters)
a - 这是要排序的数组。
fromIndex - 要排序的第一个元素(包括)的索引
toIndex - 要排序的最后一个元素(不包括)的索引
c - 用于确定阵列顺序的比较器。 空值表示应使用元素的自然顺序。
返回值 (Return Value)
此方法不返回任何值。
异常 (Exception)
ClassCastException - 如果数组包含使用指定比较器无法相互比较的元素。
IllegalArgumentException - 如果fromIndex“toIndex
ArrayIndexOutOfBoundsException - 如果fromIndex“0或toIndex”a.length
例子 (Example)
以下示例显示了java.util.Arrays.sort()方法的用法。
package com.iowiki;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class ArrayDemo {
public static void main(String[] args) {
// initializing unsorted short array
Short sArr[] = new Short[]{3, 13, 1, 9, 21};
// let us print all the elements available in list
for (short number : sArr) {
System.out.println("Number = " + number);
}
// create a comparator
Comparator<Short> comp = Collections.reverseOrder();
// sorting array with reverse order using comparator from 0 to 2
Arrays.sort(sArr, 0, 2, comp);
// let us print all the elements available in list
System.out.println("short array with some sorted values(1 to 4) is:");
for (short number : sArr) {
System.out.println("Number = " + number);
}
}
}
让我们编译并运行上面的程序,这将产生以下结果 -
Number = 3
Number = 13
Number = 1
Number = 9
Number = 21
short array with some sorted values(1 to 4) is:
Number = 13
Number = 3
Number = 1
Number = 9
Number = 21