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.
Re: Sorting 2-dimentional array has different size
Arrays.sort with a custom comparator which compares the lenght of two arrays?
Re: Sorting 2-dimentional array has different size
Thanks, but how can I do that?
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....
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.
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.
Re: Sorting 2-dimentional array has different size
Thanks a lot. It works properly now.