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:
Post a Comment