Search code examples
javaarrayssortingmultidimensional-arrayalphabetized

Alphabetizing a 2d array in java


I have a 2d array containing first name, last name, and a third irrelevant piece of data on each row. I need to alphabetize each row based on last name. How can I accomplish this?

I've tried using java.util.Arrays.sort(array[0]); but I can only get it to sort one row or one column. I need to keep the first name and last name together and sort by last name.

so say i have this array

String array [][]=new String[3][2];
       array[0][0]="Kyle";
       array[0][1]="Johnson";
       array[1][0]="Drew";
       array[1][1]="Anderson";
       array[2][0]="Jacob";
       array[2][1]="Peterson";

which is build like this

Kyle | Johnson

Drew | Anderson

Jacob| Peterson

and i need it to end up like this

Drew | Anderson

Kyle | Johnson

Jacob| Peterson


Solution

  • You can use String.compareTo(String) to get the lexicographic ordering of 2 strings and formulate you own function to do that. The rules are simple (pseudo code):

    be [s1,d1] // i.e s1 = Kyle, d1 = Johnson
    be [s2,d2]
    if (s1 < s2)  // means "Does s1 should come before s2 lexicographically" ie. s1.compareTo(s2) 
        [s1,d1] < [s2,d2]
    else if (s1 > s2)
        [s2,d2] < [s1,d1]
    else
        if (d1 < d2)
          etc...
    

    see String.compareTo & String.compareToIgnoreCase to understand the return values of these methods