Home arrow static arrow Java Programming [Archive] - how to sort a dimensional array according to the column number
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - how to sort a dimensional array according to the column number
This topic has 2 replies on 1 page.

Posts:1
Registered: 8/5/04
how to sort a dimensional array according to the column number  
Aug 5, 2004 5:21 AM



 
Hello,

I am trying to sort a 2 dimensional array of doubles according to some columns.

For example

(unsorted)
1 1 0
0 3 1
0 1 0
1 3 0
1 1 1

sorted according to first , then second, then third column should be
0 1 0
0 3 1
1 1 0
1 1 1
1 3 0

The only way out that I see is to do a bubble sort on each column, starting with the least important one, finishing with the most important one. (because the bubble sort will preserve the previous sorts).

This solution looks really inefficient. Any better ideas ?
 

Posts:743
Registered: 7/12/01
Re: how to sort a dimensional array according to the column number  
Aug 5, 2004 5:40 AM (reply 1 of 2)



 
javax.util.Arrays and Collections have a generic sort. Possibly you have to implement a compareTo in a Comparable object.
Look into the API documentation.
 

Posts:5,965
Registered: 5/17/03
Re: how to sort a dimensional array according to the column number  
Aug 5, 2004 7:31 AM (reply 2 of 2)



 
You have to supply a Comparator with the Arrays.sort call.

A 2 dimensional array is basically an array of arrays. A Comparator is an interface with just one method called compare with this signature,

int compare(Object o1, Object o2)

The sorting method will sort the first dimension of the array and it will call the compare method with the objects it finds in it (which are second dimension arrays). Compare is supposed to return a negative int if o1 < o2, a 0 if o1 == o2 and a positive int if o1 > o2.

A comparator for the job could look something like this,
class MyComparator implements Comparator {   public int compare(Object o1, Object o2) {      double[] a1 = (double[])o1; // second dimension arrays        double[] a2 = (double[])o2; // must be same length      for (int i=0; i<a1.length; i++) { // establish order by comparing         if (a1[i] < a2[i]) return -1;       // array elements         else if (a1[i] > a2[i]) return 1; // from left to right      }      return 0; // arrays are equal   }}//MyComparator mc = new MyComparator(); // instance of comparatorArrays.sort(arr,mc); // sort 2D array using comparator to handle 2'nd dim

The above isn't tested.
 
This topic has 2 replies on 1 page.