Java中Array.sort()使用方法

Java的Arrays类有一个sort()方法,它被定义为静态方法,在文件中导入Array的包可以直接调用该函数。
如下图可知 sort() 有很多种构造函数
在这里插入图片描述
我们可将其分成4类,简单介绍它的使用方法如下:

  1. Arrays.sort(int[] a)
  2. Arrays.sort(int[] a, int fromIndex, int toIndex)
  3. Arrays.sort(T[] a, Comparator<? super T> c)
  4. Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)

1. Arrays.sort(int[] a)

这种形式是对数组种所有元素进行排序,默认顺序,从小到大升序排列。

import java.util.Arrays;

public class main {
    public static void main(String[] args) {
        int[] a = {3,5,2,6,1,7,8};
        Arrays.sort(a);
        for (int i = 0; i < a.length; i ++){
            System.out.print(a[i] + " ");
        }
    }
}
//input: a = {3,5,2,6,1,7,8}
//output: 1 2 3 5 6 7 8 

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

数组中某一段 (例如 a[0,5]) 排序,默认升序排列。

import java.util.Arrays;

public class main {
    public static void main(String[] args) {
        int[] a = {5,3,2,0,1,8,7,6};
        Arrays.sort(a, 0, 5);
        for (int i = 0; i < a.length; i ++){
            System.out.print(a[i] + " ");
        }
    }
}
//inpit: a = {5,3,2,0,1,8,7,6}
//output: 0 1 2 3 5 8 7 6 

3. Arrays.sort(T[] a, Comparator<? super T> c)

改变默认排序方式,让数组从大到小排列,降序 该怎么做呢?有一点点复杂,如下

import java.util.Arrays;
import java.util.Comparator;

public class main {
    public static void main(String[] args) {
        Integer[] a = {5,3,2,0,1,8,7,6};
//        Comparator cmp = new MyComparator();
        Arrays.sort(a, new MyComparator());
        for (int i = 0; i < a.length; i ++){
            System.out.print(a[i] + " ");
        }
    }
}

class MyComparator implements Comparator<Integer>{

    @Override
    public int compare(Integer o1, Integer o2) {
        if(o1 < o2){
            return 1;
        } else if (o1 > o2) {
            return -1;
        }else{
            return 0;
        }
    }
}
//input: a = {5,3,2,0,1,8,7,6}
//ouput: 8 7 6 5 3 2 1 0 

4. Arrays.sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c)

只对数组中某一段进行降序排列,代码和 上面一条类似,只是在调用函数的时候对代码稍做修改,加上排序的前后索引即可。

//Arrays.sort(a, new MyComparator());
Arrays.sort(a,0,5, new MyComparator());

//input: a = {5,3,2,0,1,8,7,6}
//output: 5 3 2 1 0 8 7 6
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值