0

请问有没有办法如何以以下方式在java中对多维数组进行排序?

让我们有这个数组结构,

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

其中每条边都有两个坐标及其权重。我需要根据每条边的权重对整个数组进行排序。仅供参考,我需要它来查找生成树。谢谢

4

2 回答 2

2

你可以使用这样的东西:

Arrays.sort(graph, new Comparator<Integer[]>() {
             @Override
             public int compare(final Integer[] entry1, final Integer[] entry2) {
              // DO SORTING STUFF HERE
            } });
于 2012-10-13T16:01:51.680 回答
1

我猜你在使用Arrays.sortComparator使用array of array. 它的工作方式类似于您在普通数组排序中所做的工作,只是稍作改动。

这就是你在你的情况下将如何做到这一点。你需要一个Comparator数组Integer[]: -

    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();
    }

印刷: -

0 1 2 
2 4 3 
于 2012-10-13T16:49:15.420 回答