Tag Archives: code

Sorting a 2-Dimensional Array in Java

Recently while working for my project, I came across this situation when I had a 2-D array and I needed to sort it twice on 2 of its columns. Consider the following 2D array:

String[][] testString = new String[][] {
    {"1", "2", "6"},
    {"4", "5", "3"}
  };

Sorting the above 2D array on zero column will give

{
    {"1", "2", "6"},
    {"4", "5", "3"}
}

whereas sorting it on second column will give

{
    {"4", "5", "3"},
    {"1", "2", "6"}
}

I did not want to do the most common as well as tedious thing, i.e. write my own sorting function like this:

public void myOwnSort(String [][] exampleArray) {
    //code for sorting the array according to my wish.
}

I wanted to avoid this for 2 resons:

  1. I would have to write the code for it ( lazy me!!).
  2. Secondly, I can possibly never match the efficiency provided by the sorting functions of java.util.Arrays

Continue reading