1

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

Example:

For example, if an array contains:

ZCD
BFE
DZA

I want it to be sorted as:

CDZ
BEF
ADZ

Code:

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.

2
  • What does that output? If you're referring to it returning an empty array, its because you are returning an empty array. You don't initialize commonCollections. Please be clear about what you mean. Commented Sep 17, 2016 at 17:41
  • How are you storing the element..We can assume and answer..better to come from you. Commented Sep 17, 2016 at 17:41

2 Answers 2

2

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]

Sign up to request clarification or add additional context in comments.

1 Comment

Hey nice catch!
0

You've almost done it, you can fix your code by debugging.

Here is an approach with java8 streams

    char[][] arr = { { 'Z', 'C', 'D' }, { 'B', 'F', 'E' }, { 'D', 'Z', 'A' } };
    char[][] sorted = IntStream.range(0, arr.length).mapToObj(i -> arr[i]).peek(x -> Arrays.sort(x)).toArray(char[][]::new);
    for (char[] js : sorted)
        System.out.println(Arrays.toString(js));

output

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.