Java数组与列表排序总结

数组排序

主要利用Arrays.sort方法及其变体

待排序数据对象:

Integer[] a = new Integer[10];
int n = 5;
Random random = new Random(2);
for (int i = 0; i < n; i ++) {
    a[i] = random.nextInt(100);
}
for (Integer ele : a)
    System.out.print(ele + " ");
System.out.println();

/*
数据样式:8 72 40 67 89 null null null null null
*/

(1)升序排列:

Arrays.sort(a, 0, n);

注意:切不可直接调用Arrays.sort(a),会报错,因为有null元素值存在。

(2)降序排列:

Arrays.sort(a, 0, n, Collections.reverseOrder());

(3)自定义排序【按照最低位数字从小到大排序】:

Arrays.sort(a, 0, n, (o1, o2) -> o1 % 10 - o2 % 10); // or Arrays.sort(a, 0, n, Comparator.comparingInt(o -> o % 10));
for (Integer ele : a)
    System.out.print(ele + " ");
System.out.println();

/*
结果:40 72 67 8 89 null null null null null 
*/

(4)如果类实现了Comparable接口,也可以直接用Arrays.sort排序。

注意:

如果是对原始数据类型例如int、double等等进行排序,Arrays.sort方法利用的是双轴快速排序,是一种不稳定的算法。

而对引用类型进行排序时,使用的是改进的归并排序,是稳定算法。

列表排序

(1)如果列表中的元素实现了Comparable接口,则直接调用Collections.sort方法进行排序:

sort(List<T> list) 
根据其元素的natural ordering对指定的列表进行排序。 

(2)自定义排序规则进行排序【该方法优先级高于第一种】:

sort(List<T> list, Comparator<? super T> c) 
根据指定的比较器引起的顺序对指定的列表进行排序。 

(3)利用流对列表进行排序:

详见博客:https://blog.csdn.net/LLF_1241352445/article/details/81002477

原文地址:https://www.cnblogs.com/doubest/p/15385621.html