# Sorting 2-dimentional array has different size

• 09-24-2012, 05:19 PM
asa
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.
• 09-24-2012, 05:27 PM
eRaaaa
Re: Sorting 2-dimentional array has different size
Arrays.sort with a custom comparator which compares the lenght of two arrays?
• 09-25-2012, 01:37 AM
asa
Re: Sorting 2-dimentional array has different size
Thanks, but how can I do that?
• 09-25-2012, 06:48 AM
eRaaaa
Re: Sorting 2-dimentional array has different size
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....
• 09-25-2012, 07:23 AM
asa
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.
• 09-25-2012, 08:38 AM
pbrockway2
Re: Sorting 2-dimentional array has different size
Quote:

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.

Quote:

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.
• 09-26-2012, 01:30 AM
asa
Re: Sorting 2-dimentional array has different size
Thanks a lot. It works properly now.