I have a problem sorting the contents of a 2D integer array (not ArrayList) in Java. My problem array path_info[ ][ ] looks something like this:
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
Each row means: node_x to node_y on Path_ID through Port_x to Port_y. Please note, each path can be one or more rows in the table.
This array is the resultant array from a routing algorithm to reach node 1 from node 8 on an undirected unweighted graph.
To reach from a source node to a destination node; for example node 1 from node 8 in the table, the path_IDs are 500, 501, 502 and 503 (PATH_IDs already sorted in column Path_ID). The problem is that I want this array to be sorted in such a way that the source node is the first node of the column “Node_x” and the destination node is the last node .of the column “Node_y”. And all the intermediate rows and columns sorted appropriately.
The resultant array should look like this (when source node is 8 and destination node is 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
I have not started writing code yet so do not have a snippet to paste. I am still trying to figure out how to achieve this. Could someone please help me?
Assuming your algorithm worked correctly, you shouldn’t ever be visiting the same node more than once. So you can just greedily look for the right nodes, but you need a good data structure so you don’t loop incessantly. This code assumes that
path_info[index][0]isnode_x, andpath_info[index][1]isnode_y. Try something like this, which runs inO(n)time for each loop: