1. 基本升序排序
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Arrays.sort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
输出:
0 1 2 3 4 5 6 7 8 9
2. 部分升序排序
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Arrays.sort(a, 0, 3);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
输出:
7 8 9 2
3. 使用自定义Comparator实现降序排序
import java.util.*;
public class Main {
public static void main(String[] args) {
Integer[] arr = {5, 4, 7, 9, 2, 12, 54, 21, 1};
// 使用匿名内部类
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return b - a;
}
});
System.out.println(Arrays.toString(arr));
// 使用Lambda表达式
Arrays.sort(arr, (a, b) -> {
return b - a;
});
System.out.println(Arrays.toString(arr));
// 使用实现了Comparator接口的具体类
Arrays.sort(arr, new compa());
System.out.println(Arrays.toString(arr));
}
}
class compa implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
}
输出:
[54, 12, 9, 7, 5, 4, 2, 2, 1, 1]
[54, 12, 9, 7, 5, 4, 2, 2, 1, 1]
[54, 12, 9, 7, 5, 4, 2, 2, 1, 1]