Java 二维数组排序 —— Arrays.sort 案例

二维数组例子,直接复制去吧。

 		int[][] arr = new int[8][];
        arr[0] = new int[]{9, 12};
        arr[1] = new int[]{1, 10};
        arr[2] = new int[]{4, 11};
        arr[3] = new int[]{8, 12};
        arr[4] = new int[]{3, 9};
        arr[5] = new int[]{6, 9};
        arr[6] = new int[]{6, 7};
        arr[7] = new int[]{1, 5};

先对数组进行排序
以x start 升序
如果 x start 相同,以 x end 升序

        Arrays.sort(points, (o1, o2) -> {
            if (o1[0] == o2[0]) {
                return o1[1] - o2[1];
            } else {
                return o1[0] - o2[0];
            }
        });

在这里插入图片描述

这个排序有个弊端。对[[-2147483646,-2147483645],[2147483646,2147483647]]这个测例会溢出。
这个是二维数组的单关键字升序

        Arrays.sort(points, Comparator.comparingInt(a -> a[0]));

在这里插入图片描述

第三种方式是第一种的改进,防止溢出的。

        Arrays.sort(points, (o1, o2) -> {
            if (o1[0] == o2[0]) {
                // 升序  o1[1]-o2[1]   <0
                // 即  o1[1]<o2[1]
                // Integer.compare(o1[1], o2[1])
                // 如果 o1[1]<o2[1]
                // Integer.compare(o1[1], o2[1]) 返回 -1 也<0
                return Integer.compare(o1[1], o2[1]);
            } else {
                return Integer.compare(o1[0], o2[0]);
            }
        });

在这里插入图片描述

二维数组根据不同列进行升序降序选择。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值