Brandex07 Brandex07 - 2 months ago 14
Java Question

How to sort each row in a 2d String array in java using Arrays.sort?

I am trying to sort each row of a 2d String array in java.

so for example, if an array contains:
ZCD
BFE
DZA
I want it to be sorted as
CDZ
BEF
ADZ

private String[] commonCollections;

private int comparisons = 0;

public Comparable[] findCommonElements(Comparable[][] collections){

for(int i = 0; i < collections.length; i++){
Arrays.sort(collections[i]);

}

for(int i = 0; i <collections[0].length; i++){
System.out.print(collections[0][i] + "\n");
}


return commonCollections;
}


Thanks. With the code above, its not sorting for some reason.

Answer

Your sorting seems fine. The way you are printing is the issue.

Is this what you want?

public class Main {


    public  static Comparable[][] findCommonElements(Comparable[][] collections){


        for(int i = 0; i < collections.length; i++){
            Arrays.sort(collections[i]);

        }

        return collections;
    } 

   public static void main(String[] args) {

    Character [][]input= {{'Z','C','D'},{'B','F','E'},{'D','Z','A' }};

    Comparable[][] output = findCommonElements(input);

    for(int i = 0; i <output.length; i++){
        System.out.print(Arrays.toString(output[i]) + "\n");
    }     
  }
}

Which produces this output:

[C, D, Z] [B, E, F] [A, D, Z]

Comments