Arrays.sort()自定义排序的实现

1. Arrays.sort(T[] a)是对数组元素按字典序进行升序排列

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);
        System.out.println(Arrays.toString(arr));
    }   
}

output: 

[1, 2, 4, 5, 7, 9, 12, 21, 54]

 

2. Arrays.sort(T[] a, Comparator<? Super T> c)用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>() {
            public int compare(Integer a, Integer b) {
                return b-a;
            }
        });
        System.out.println(Arrays.toString(arr));    
    }   
}

output:

[54, 21, 12, 9, 7, 5, 4, 2, 1]

 

3. Arrays.sort(T[] a, int fromIndex, int toIndex)实现对数组中的一部分进行排序

 对数组a中,index属于[fromIndex, toIndex)的元素进行排序

 同样,Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator<? Super T> c)可实现自定义排序规则

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, 2, 7);
        System.out.println(Arrays.toString(arr));    
    }   
}

output:

[5, 4, 2, 7, 9, 12, 54, 21, 1]

 

 

posted @ 2018-10-27 15:08  macy_zhang  阅读(14387)  评论(0编辑  收藏  举报