数组排序

1.对一个数组的所有元素进行排序,并且是按从小到大的顺序。

Arrays.sort(int[] a)

2.对数组部分排序,也就是对数组a的下标从fromIndex到toIndex-1的元素排序

Arrays.sort(int[] a, int fromIndex, int toIndex)

3.从大到小排序

 package test;
 
 import java.util.Arrays;
 import java.util.Comparator;

 public class Main {
     public static void main(String[] args) {
         //注意,要想改变默认的排列顺序,不能使用基本类型(int,double, char)
         //而要使用它们对应的类
         Integer[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
         //定义一个自定义类MyComparator的对象
         Comparator cmp = new MyComparator();
         Arrays.sort(a, cmp);
         for(int i = 0; i < a.length; i ++) {
             System.out.print(a[i] + " ");
         }
     }
 }
 //Comparator是一个接口,所以这里我们自己定义的类MyComparator要implents该接口
 //而不是extends Comparator
 class MyComparator implements Comparator<Integer>{
     @Override
     public int compare(Integer n1, Integer n2) {
         //如果n1小于n2,我们就返回正值,如果n1大于n2我们就返回负值,
         //这样颠倒一下,就可以实现反向排序了
         if(n1 < n2) { 
             return 1;
         }else if(n1 > n2) {
             return -1;
         }else {
             return 0;
         }
     }
     
 }
原文地址:https://www.cnblogs.com/sun27/p/11126536.html