0

Please is there a way how to sort multidimensional array in java in the following manner?

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

simekadam
  • 7,334
  • 11
  • 56
  • 79
  • So..I think default array sort in Java cant do that..But I do not want implement own version of mergesort (its fast), it would be quite time-consuming for me.. – simekadam Oct 13 '12 at 16:01
  • 2
    I learned a new word recently: Object Denial (cf. http://stackoverflow.com/questions/3725703/how-to-store-more-than-one-string-in-a-map/3725728#3725728). If you find it hard or tedious to work with your chosen representation, it may not be optimal for your task... – Anders R. Bystrup Oct 13 '12 at 16:02
  • @Anders Rostgaard Bystrup since I need to make it as fast as possible I can't have every edge as separate instance of some Edge class..I would like to do it so, but it would possibly fail the test (its home assigment from advanced algorithms class)..Our teacher said we should avoid using objects... – simekadam Oct 13 '12 at 17:45
  • So I created Edge class have dozens and even with dozens of intances created it runs pretty fast..Weird:D – simekadam Oct 13 '12 at 20:37

2 Answers2

2

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
            } });
Vincent Koeman
  • 751
  • 3
  • 9
1

I guess you are having problem with using Arrays.sort and Comparator with an array of array. It works similar to what you do in normal Array sorting, with a little change.

This is how you would do this in your case. You need a Comparator for an Integer[] array: -

    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 
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525