I am looking to sort the following array based on the values of [][0]
double[][] myArr = new double[mySize][2];
so for example, 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 having to implement my own sort.
In a 2D array, a cell has two indexes one is its row number, and the other is its column number. Sorting is a technique for arranging elements in a 2D array in a specific order. The 2D array can be sorted in either ascending or descending order.
Make the 2D array into a separate simple (1D) array (STEP 1). Then use the Arrays. sort() method to sort the simple array (STEP 2). Then set each space of the 2D array to be the number of columns across (X-coordinate where the space will be changed) multiplied by the number of spaces per row in the 2D array.
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]); } });
JAVA-8: Instead of that big comparator, we can use lambda function as following-
Arrays.sort(array, Comparator.comparingDouble(o -> o[0]));
Welcome Java 8:
Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With