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]

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM