在Java中对复杂数组进行排序

时间:2012-12-13 19:07:00

标签: java sorting multidimensional-array

我在使用Java排序2D整数数组(不是ArrayList)的内容时遇到问题。我的问题数组path_info[ ][ ]看起来像这样:

Node_x Node_y Path_ID Port_x Port_y
  4      6      500     3       2
  6      8      500     3       2      
  4      9      501     2       3
  9      3      501     2       2      
  2      3      502     3       2      
  1      5      503     2       3 
  5      2      503     2       2

每一行表示:在Path_ID上通过Port_x到Port_y的node_x到node_y。请注意,每个路径可以是表中的一行或多行。

此数组是路由算法的结果数组,用于在无向未加权图上从节点8到达节点1。

从源节点到达目标节点;例如,表中节点8的节点1,path_ID是500,501,502和503(PATH_ID已经在列Path_ID中排序)。问题是我希望对这个数组进行排序,使得源节点是列“Node_x”的第一个节点,目标节点是列“Node_y”的最后一个节点。并且所有中间行和列都适当地排序。

结果数组应如下所示(当源节点为8且目标节点为1时):

Node_x Node_y Path_ID Port_x Port_y
  8      6      500     2      3
  6      4      500     2      3     
  4      9      501     2      3
  9      3      501     2      2
  3      2      502     2      3
  2      5      503     2      2
  5      1      503     3      2

我还没有开始编写代码,所以没有要粘贴的代码段。我仍在试图弄清楚如何实现这一目标。有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

Arrays.sort()与自定义比较器配合使用,该比较器适用于一维数组(2D数组的元素)

答案 1 :(得分:0)

假设您的算法运行正常,您不应该多次访问同一节点。因此,您可以贪婪地寻找正确的节点,但是您需要一个良好的数据结构,因此您不必不断循环。此代码假定path_info[index][0]node_xpath_info[index][1]node_y。尝试这样的事情,每个循环在O(n)时间运行:

import java.util.*;

public class GraphSorter {
  public static void main(String[] args) {
    int[][] graph = new int[][]{{9, 3}, {6, 4}, {3, 2}, {8, 6}, {5, 1}, {4, 9}, {2, 5} }; 
    LinkedList<int[]> myList = path(graph, 8);
    for (int[] edge : myList) {
      System.out.println(Arrays.toString(edge));
    }
  }

  public static LinkedList<int[]> path(int[][] path_info, int source) {
    HashMap<Integer, int[]> nodeXmap = new HashMap<Integer, int[]>();
    HashMap<Integer, int[]> nodeYmap = new HashMap<Integer, int[]>();
    LinkedList<int[]> foundPath = new LinkedList<int[]>();

    for(int i = 0; i < path_info.length; i++) {
      // We already found an edge with this node_x edge, turn it around
      if(nodeXmap.containsKey(path_info[i][0])) {
        int tmp = path_info[i][0];
        path_info[i][0] = path_info[i][1];
        path_info[i][1] = tmp;
      }
      nodeXmap.put(path_info[i][0], path_info[i]);
      nodeYmap.put(path_info[i][1], path_info[i]);
    }

    int current = source;
    // Use our maps to lookup where the next edge exists in our path,
    // since our input is guaranteed to be unique
    for(int i = 0; i < path_info.length; i++) {
      int[] currentEdge = nodeXmap.get(current);
      if (currentEdge == null) {
        currentEdge = nodeYmap.get(current);
        current = currentEdge[0];
      } else {
        current = currentEdge[1];
      }
      foundPath.add(currentEdge);
      nodeXmap.remove(currentEdge[0]);
      nodeYmap.remove(currentEdge[1]);
    }

    return foundPath;
  }
}