7 Replies Latest reply: May 29, 2007 3:36 PM by 807600 RSS

    sorting 2D array

    807598
      Hi, I am having problems sorting the 2nd element of a 2D array. I can do it in perl in two lines but don't know the best way for Java. Here is a small example:

      String[][] names = new String[3][2];
      names[0][0] = "ann";
      names[0][1] = "10";

      names[1][0] = "barry";
      names[1][1] = "5";

      names[2][0] = "mark";
      names[2][1] = "8";


      so I would like to sort by the score in the 2nd col of the array, so I should be able to print out in descending order:

      ann 10
      mark 8
      barry 5

      I can see how to do this with Arrays.sort(names) if it was a 1D array, but for 2D ? Does Java make me convert to another data type to do this ? seems a little awkward, thanks for your help
        • 1. Re: sorting 2D array
          807598
          It's a little more difficult in Java.
            public static void main(String[] args) {
              String[][] names = new String[3][2];
              names[0][0] = "ann";
              names[0][1] = "10";
          
              names[1][0] = "barry";
              names[1][1] = "5";
          
              names[2][0] = "mark";
              names[2][1] = "8";
              for(int i = 0; i < names.length; i++) {
                System.out.println(names[0] + ", " + names[i][1]);
          }

          java.util.Arrays.sort(names, new java.util.Comparator<String[]>() {
          public int compare(String[] o1, String[] o2) {
          if(Integer.parseInt(o1[1]) > Integer.parseInt(o2[1])) {
          return 1;
          } else if(Integer.parseInt(o1[1]) < Integer.parseInt(o2[1])) {
          return -1;
          } else {
          return 0;
          }
          }

          }
          );
          for(int i = 0; i < names.length; i++) {
          System.out.println(names[i][0] + ", " + names[i][1]);
          }

          }

          http://java.sun.com/j2se/1.5.0/docs/api/java/util/Comparator.html
          • 2. Re: sorting 2D array
            807598
            Hi, I am having problems sorting the 2nd element of a
            2D array. I can do it in perl in two lines but don't
            know the best way for Java.
            The "best" way is to encapsulate the related information in an object (what does the number signify?) and sort the objects using the existing API.

            Example:
            import java.util.*;
            
            public class Demo {
                public static void main(String... args) {
                    new Demo().go();
                }
                
                void go() {
                    List<Thing> list = Arrays.asList(new Thing[] {
                        new Thing("ann", 10),
                        new Thing("barry", 5),
                        new Thing("mark", 8),
                    });
                    Collections.sort(list, Thing.BY_VALUE);
                    for (Thing t : list) {
                        System.out.println(t);
                    }
                }
            }
            
            final class Thing {
                public static Comparator<Thing> BY_VALUE = new ValueComparator();
                private String name;
                private int value;
                
                public Thing(String name, int value) {
                    this.name = name;
                    this.value = value;
                }
                
                public String toString() {
                    return name + " " + value;
                }
                
                private static final class ValueComparator 
                        implements Comparator<Thing> {
                    public int compare(Thing t1, Thing t2) {
                        if (t1.value < t2.value) return -1;
                        else if (t1.value > t2.value) return 1;
                        else return 0;
                    }
                }
            }
            Output:

            ann 10
            mark 8
            barry 5
            • 3. Re: sorting 2D array
              807598
              Thanks so much for the help, I will use Comparator ..seems such a tedious requirement for something so simple though! ..thanks :)
              • 4. Re: sorting 2D array
                807598
                Check out http://java.sun.com/j2se/1.3/docs/api/java/util/TreeMap.html, if you are building a comparator anyway this could make your code a little cleaner. Items would be sorted as they are added and you have an easier way of retrieving them.
                • 5. Re: sorting 2D array
                  807598
                  I've got a similar problem. I have a 2d array of strings which needs to be sorted in descending order. Tried to adapt the examples given, but i'm reading in information from a simple text file.

                  Any help would be appreciated.

                  Thanks
                  • 6. Re: sorting 2D array
                    807600
                    bluecoder-

                    I know this is a Java forum, but I was actually searching for this information in Perl. You mentioned it is simple to do this type of column sorting for 2D arrays in perl, what is the code for doing this?

                    Thanks,
                    Alex Muir
                    • 7. Re: sorting 2D array
                      807600
                      Bluecoder hasn't posted in a year and a half, what makes you think he's still around to answer your question? You'd do better to find a perl forum where there are people that know perl posting.