Dax Durax Dax Durax - 5 months ago 34
Java Question

java Arrays.sort 2d array

SO,

I am looknig to sort the following array based on the values of [][0]

double[][] myArr = new double[mySize][2];


so for ex, myArr contents is:

1 5
13 1.55
12 100.6
12.1 .85


I want it to get to :

1 5
12 100.6
12.1 .85
13 1.55


I am looking to do this without have to implement my own sort. Any help is appreciated, thanks.

Answer

Use Overloaded Arrays#Sort(T[] a, Comparator c) which takes Comparator as the second argument.

double[][] array= {
{1, 5},
{13, 1.55},
{12, 100.6},
{12.1, .85} };

java.util.Arrays.sort(array, new java.util.Comparator<double[]>() {
    public int compare(double[] a, double[] b) {
        return Double.compare(a[0], b[0]);
    }
});