java数组排序

1. 一般思路

就是用现成的库函数,一般是调用Arrays.sort()方法。
Arrays.sort()重载了四类方法

sort(T[] a):对指定T型数组按数字升序排序。
sort(T[] a,int formIndex, int toIndex):对指定T型数组的指定范围按数字升序排序。
sort(T[] a, Comparator<? supre T> c): 根据指定比较器产生的顺序对指定对象数组进行排序。
sort(T[] a, int formIndex, int toIndex, Comparator<? supre T> c): 根据指定比较器产生的顺序对指定对象数组的指定对象数组进行排序。

一般的调用Arrays.sort()就ok了,如果是自定义类型,就需要加一个Comparator类,里面实现。

   * @param o1 the first object to be compared.
     * @param o2 the second object to be compared.
     * @return a negative integer, zero, or a positive integer as the
     *         first argument is less than, equal to, or greater than the
     *         second.
     int compare(T o1, T o2)

返回是一个int类型,负数是代表第一个数01小于o2,正数是代表大于。跟golang 的不大一样,感觉golang的比较函数逻辑更自然一点,直接返回 bool类型。详情请见 go-sort排序

2. 直接排序,利用库函数

比如我有一个数组

Integer[] a = { 9, 8, 7, 2, 3, 4, 1, 0, 6, 5 }; 
Arrays.sort(a);
3. 一维数组,带利用库函数的逆序排序
Arrays.sort(a, Collections.reverseOrder());
4. 一维数组,带Comparator的排序 ,逆序排序
  Arrays.sort(a,new Comparator<Integer>(){
            public int compare(Integer x,Integer y){
                return y-x;
            }
     });

这个可以用lambda 简化成:

Arrays.sort(a,(Integer x,Integer y)->{return y-x;});
5. 二维数组,Comparator排序,
int[][] nums = new int[][]{{2,4},{5,6},{1,2},{7,8},{7,9}};

一个典型的场景是合并区间.

Arrays.sort(nums,new Comparator<int[]>(){
             public int compare(int[] a, int[] b){
                 return a[0]-b[0];
             }
         });

Comparator 里面的T是 int[] , compare 函数参数也是int[] ,要一致。

6. 二维数组,lambda 简化排序
 Arrays.sort(nums,(a,b)->{return a[0]-b[0];});
posted @ 2020-12-04 12:29  过去的我  阅读(415)  评论(0编辑  收藏  举报