简体   繁体   English

用Java排序多维数组

[英]Sort multidimensional array in Java

Please is there a way how to sort multidimensional array in java in the following manner? 请问有一种方法可以通过以下方式在Java中对多维数组进行排序吗?

Lets have this array structure, 让我们拥有这个数组结构

int graph[][] = new int[edges][3];

where every edge will have two coordinates and its weight. 每个边缘都有两个坐标及其权重。 And I need to sort the whole array according to the weight of every edge. 我需要根据每个边缘的权重对整个数组进行排序。 Just FYI I need it for finding spanning trees. 仅供参考,我需要它来查找生成树。 Thanks 谢谢

You can use something like this: 您可以使用如下形式:

Arrays.sort(graph, new Comparator<Integer[]>() {
             @Override
             public int compare(final Integer[] entry1, final Integer[] entry2) {
              // DO SORTING STUFF HERE
            } });

I guess you are having problem with using Arrays.sort and Comparator with an array of array . 我猜您有使用问题Arrays.sortComparatorarray of array It works similar to what you do in normal Array sorting, with a little change. 它的工作原理与您在常规Array排序中的工作类似,只是有所不同。

This is how you would do this in your case. 这就是您要如何处理的情况。 You need a Comparator for an Integer[] array: - 您需要一个Integer[]数组的Comparator器:-

    Integer graph[][] = new Integer[2][3];
    graph[0][0] = 2;
    graph[0][1] = 4;
    graph[0][2] = 3;

    graph[1][0] = 0;
    graph[1][1] = 1;
    graph[1][2] = 2;


    Arrays.sort(graph, new Comparator<Integer[]>() {
        @Override
        public int compare(Integer[] o1, Integer[] o2) {

            return o1[2] - o2[2];
        }
    });


    for (Integer[] outerArr: graph) {
        for (Integer val: outerArr) {
            System.out.print(val + " ");
        }
        System.out.println();
    }

Prints: - 打印:-

0 1 2 
2 4 3 

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

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