# Thread: Sorting 2-dimentional array has different size

1. Member
Join Date
May 2012
Posts
11
Rep Power
0

## Sorting 2-dimentional array has different size

Hello,

I am looking for a fast way to sort a 2-dimentional array with different size as per its row size in descending order.

EX:
A = {(5,9,3), (5,9,3,4),(5,9,3,4,2)}
After sorting should be
A= {(5,9,3,4,2), (5,9,3,4), (5,9,3)}
because A[2].length > A[1].length > A[0].length

Thanks.
Last edited by asa; 09-25-2012 at 05:28 AM.

2. Senior Member
Join Date
Oct 2010
Location
Germany
Posts
786
Rep Power
5

## Re: Sorting 2-dimentional array has different size

Arrays.sort with a custom comparator which compares the lenght of two arrays?

3. Member
Join Date
May 2012
Posts
11
Rep Power
0

## Re: Sorting 2-dimentional array has different size

Thanks, but how can I do that?

4. Senior Member
Join Date
Oct 2010
Location
Germany
Posts
786
Rep Power
5

## Re: Sorting 2-dimentional array has different size

Java Code:
```		Arrays.sort(yourArray, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.valueOf(o2.length).compareTo(o1.length);
}
});```
I hope I haven't done your homework....

5. Member
Join Date
May 2012
Posts
11
Rep Power
0

## Re: Sorting 2-dimentional array has different size

Thanks, but when I couldn't do it by this way.
sort takes T[] as a first parameter.
So it doesn't accept my array. My array is a string array not an int, will it work on this way?

Thanks.

6. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,565
Rep Power
12

## Re: Sorting 2-dimentional array has different size

but when I couldn't do it by this way.
So, what happened when you tried? Post your code and if there were compiler messages you can't understand post them as well. If your code runs but doesn't produce the output you described, say what it does do at runtime.

My array is a string array not an int, will it work on this way?
It might have been a bit misleading to use 5, 9, 3, ... as example when you're working with strings. But yes, writing a comparator as in #4 but using String[] rather than int[] is the way to go.

7. Member
Join Date
May 2012
Posts
11
Rep Power
0

## Re: Sorting 2-dimentional array has different size

Thanks a lot. It works properly now.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•