Thursday, April 5, 2007

Java: Sort a 2-dimensional array using Arrays.sort()

While working with a 2-dimensional array (modeled as rows and attributes), one may have to sort the array based on different attributes. However, Arrays.sort(), by default, sorts a 2-dimensional array by its first attribute.

Instead of writing a full-fledged sorting code (mergesort or heapsort, etc.), we can use Arrays.sort() by just redefining its Comparator by specifying the compare() method to sort the array as needed.

You can also change it to return the results in ascending or descending order.
//Using Arrays.sort to sort the array "result[][]", based on the attribute 'd' 
double result[][] = new double[m][n]; // 'm' rows, 'n' attributes
int d=0; // 0 <= d <= n-1
java.util.Arrays.sort(result, new java.util.Comparator() {
public int compare(double[] o1, double[] o2) {
if(o1[d]>o2[d]) return 1; // -1 for descending order
else if(o1[d]<o2[d]) return -1; // 1 for descending order
else return 0;

No comments:

Back to Top