Home > front end >  Sort 2D array elements in descending order
Sort 2D array elements in descending order

Time:10-20

Say I have a 2D array of n length, is there a way I can sort the 2D array in descending order according to the size of the sub-array

For example:

{{"1","b","g"},{"e","3"},{"r","2","9","a"},{"2"}}

would become:

{{"r","2","9","a"},{"1","b","g"},{"e","3"},{"2"}}

CodePudding user response:

String tab[][] = new String[][]{{"1","b","g"},{"e","3"},{"r","2","9","a"},{"2"}};
String temp[];          
    for (int i = 0; i <tab.length; i  ) {     
        for (int j = i 1; j <tab.length; j  ) {     
            if(tab[i].length < tab[j].length) {
               temp = tab[i];    
               tab[i] = tab[j];    
               tab[j] = temp;    
             }     
          }     
      }             
System.out.println(Arrays.deepToString(tab));

output: [[r, 2, 9, a], [1, b, g], [e, 3], [2]]

CodePudding user response:

More details are required on this question.

Considering that the given data structure is an array it would look like -

[["1","b","g"],["e","3"],["r","2","9","a"],["2"]]

To sort this array in python consider the below given code :-

a = [["1","b","g"],["e","3"],["r","2","9","a"],["2"]]
a.sort(key=len)

It will sort the array according to the length of subarrays

  • Related