-2

Assume I have this 2D array:

array[0][] = {5,B,2}
array[1][] = {9,R,4}
array[2][] = {3,B,1}
array[3][] = {1,R,8}

How can I sort this array in such a way that this is the output:

array[0][] = {3,B,1}
array[1][] = {5,B,2}
array[2][] = {9,R,4}
array[3][] = {1,R,8}

Basically sorting them based on the [i][2] element.

This is how I declared the array:

String[][] splitnodes = new String[7][];

Is it even possible? If it is, how?

Thanks!

2 Answers2

0

One approach would be to implement a "normal search" like insertion sort, where you only compare the second element, and then carry the rest of the elements

David Huang
  • 63
  • 1
  • 7
0

You can use any sorting tecnique and in the step involving the comparision you need to compare the 2nd element of each sub array. Using the utility method provided in the J0DK you may also use sortmethod defined in Arrays.java.

java.util.Arrays.sort(array, new 
    java.util.Comparator<String[]> () {
        public int compare(String[] a, String[] b) {
             return Integer.compare(Integer.parseInt( a[2]), Integer.parseInt(b[2]));
        }
});
nits.kk
  • 5,204
  • 4
  • 33
  • 55