简体   繁体   English

Java - 二维整数数组的多级排序

[英]Java - Multilevel sort of a 2D array of integers

I'm trying to figure out how to do a multilevel sort of a 2D array of integers in java, where the first numbers takes priority.我试图弄清楚如何在java中对二维整数数组进行多级排序,其中第一个数字优先。

so a dataset like this:-所以像这样的数据集:-

{1,2}
{2,9}
{2,7}
{2,8}
{5,6}
{5,8}
{5,2}
{4,1}
{4,4}

Should return something like this:-应该返回这样的东西:-

{1,2}
{2,7}
{2,8}
{2,9}
{4,1}
{4,4}
{5,2}
{5,6}
{5,8}

How about this:这个怎么样:

for(int i = 0; i < arr.length; i++)
{
    int min = i;

    for(int j = i; j < arr.length; j++)
    {
        if(arr[min][0] > arr[j][0])
        {
            min = j;
        }
    }

    int[] temp = arr[min];
    arr[min] = arr[i];
    arr[i] = temp;
}

for(int i = 0; i < arr.length; i++)
{
    int min = i;
    for(int j = i; j < arr.length; j++)
    {
        if(arr[j][0] != arr[i][0])
        break;

        if(arr[min][1] > arr[j][1])
        min = j;
    }

    int[] temp = arr[min];
    arr[min] = arr[i];
    arr[i] = temp;
}

Here's a way to do it:这是一种方法:

import java.util.*;

public class Test
{
     public static void main(String []args)
     {
         Integer[][] a = {
                    {1,2},
                    {2,9},
                    {2,7},
                    {2,8},
                    {5,6},
                    {5,8},
                    {5,2},
                    {4,1},
                    {4,4}
                  };

        Arrays.sort(a, new Comparator<Integer[]>()
        {
            public int compare(Integer[] a, Integer[] b)
            {
                int res = a[0].compareTo(b[0]);
                if(res!=0)
                    return res;
                return a[1].compareTo(b[1]);
            }
        });

        System.out.println(Arrays.deepToString(a));
     }
}

Here's a solution using Comparator.class这是使用Comparator.class的解决方案

int[][] array = {{1,2},{2,9}, {2,7},{2,8},{5,6},{5,8},{5,2},{4,1},                    {4,4}};

Arrays.sort(array, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[0] == o2[0]){
                    return o1[1]-o2[1];
                }else {
                    return o1[0]-o2[0];
                }
            }
        });
System.out.println(Arrays.deepToString(array));

Prints this : [[1, 2], [2, 7], [2, 8], [2, 9], [4, 1], [4, 4], [5, 2], [5, 6], [5, 8]]打印: [[1, 2], [2, 7], [2, 8], [2, 9], [4, 1], [4, 4], [5, 2], [5, 6], [5, 8]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM