- How to sort two dimensional array in Java? [closed]
- 1 Answer 1
- Related
- Hot Network Questions
- 2D Array Sorting in Java
- Examples of 2D Array Sorting in Java
- Example #1
- Example #2
- Example #3
- Conclusion
- Recommended Articles
- How to sort a two-dimensional array on column values in java / How to sort a two-dimensional array in java
- Share if it’s worth .
How to sort two dimensional array in Java? [closed]
I have a two dimensional double array. I need to sort my based column 1 in descending order. How can I sort my two dimensional array in descending order. Sample data and code are the following:
package mypro.com; public class SortDoubleArrary < public static void main(String agrs[]) throws Exception< double[][] testdatset=new double[5][2]; testdatset[0][0]=20.0; testdatset[0][1]=0.20; testdatset[1][0]=100.0; testdatset[1][1]=0.50; testdatset[2][0]=10.0; testdatset[2][1]=0.95; testdatset[3][0]=220.0; testdatset[3][1]=0.35; testdatset[4][0]=140.0; testdatset[4][1]=0.10; >>
10.0 0.95 100.0 0.5 220.0 0.35 20.0 0.2 140.0 0.1
1 Answer 1
There is an overloaded sort method in java.util.Arrays class which takes two arguments: the array to sort and a java.util.Comparator object.
You can add the following lines of code with your program to get the expected result.
import java.util.Arrays; import java.util.Comparator; Arrays.sort(testdatset, new Comparator() < @Override public int compare(double[] o1, double[] o2) < return Double.compare(o2[1], o1[1]); >>);
Related
Hot Network Questions
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
2D Array Sorting in Java
The following article provides an outline for 2D Array Sorting in Java. An array of arrays can be a two-dimensional array. The matrices that make up the 2D array represent a collection of rows and columns. Because the elements of 2D arrays can get accessed at random, we can access the individual cells in a 2D array using their indexes, just like we can with one-dimensional arrays.
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 in either ascending or descending order. Let’s see how to sort different ways the 2D array in Java in ascending and descending order.
Examples of 2D Array Sorting in Java
Different examples are as below:
Example #1
Example for 2D array sorting in Java to sort all elements of a 2D Array.
package jex; import java.util.*; public class demo < // using bubble sort to sort 2D array // sort 2D array same as it is in a 1D array of size n * m public static void sort(int arr[][]) < int i, j, temp; int n=arr.length; int m=arr[0].length; for (i = 0; i < n * m - 1; ++i) < for (j = 0; j < n * m - 1 - i; ++j) < if (arr[j / m][j % m] >arr[(j + 1) / m][(j + 1) % m]) < temp = arr[(j + 1) / m][(j + 1) % m]; arr[(j + 1) / m][(j + 1) % m] = arr[j / m][j % m]; arr[j / m][j % m] = temp; >> > > public static void print(int arr[][]) < int i, j; int n=arr.length; int m=arr[0].length; for (i = 0; i < n; ++i) < for (j = 0; j < m; ++j) < System.out.print(arr[i][j]+" "); >System.out.println(); > > public static void main(String[] args) < Scanner sc=new Scanner(System.in); int[][] arr=< < 5, 12, 17, 12, 23>, < 1, 2, 4, 6, 8>, , < 3, 18, 9, 15, 25>>; System.out.println("Array Before Sorting is : "); print(arr); sort(arr); System.out.println("Array After Sorting is : "); print(arr); > >
As in the above program, the sort() method is useful to iterate each element of a 2D array, and when the current element is greater than the next element, then swap the numbers. Finally, the print method displays all the elements of the 2D array. In the main function, the 2D array is created and printed after and before calling the sort() function, as shown in the above output.
Example #2
Example for 2D array sorting in Java to sort all elements of a 2D array by column-wise.
package jex; import java.util.*; public class demo < public static void sort(int arr[][]) < int i, j,k, temp; int n=arr.length; int m=arr[0].length; for (k = 0; k < m; ++k) < for (i = 0; i < n; ++i) < for (j = 0; j < n - 1 - i; ++j) < if (arr[j][k] >arr[j + 1][k]) < temp = arr[j + 1][k]; arr[j + 1][k] = arr[j][k]; arr[j][k] = temp; >> > > > public static void print(int arr[][]) < int i, j; int n=arr.length; int m=arr[0].length; for (i = 0; i < n; ++i) < for (j = 0; j < m; ++j) < System.out.print(arr[i][j]+" "); >System.out.println(); > > public static void main(String[] args) < Scanner sc=new Scanner(System.in); int[][] arr=< < 5, 12, 17, 12, 23>, < 1, 2, 4, 6, 8>, , < 3, 18, 9, 15, 25>>; System.out.println("Array Before Sorting is : "); print(arr); sort(arr); System.out.println("Array After Sorting is : "); print(arr); > >
As in the above rewrite program, the sort() method is useful to iterate each element of a 2D array and sort the array column-wise. Finally, the print method displays all the elements of the 2D array. In the main function, the 2D array is created and printed after and before calling the sort() function, as shown in the above output.
Example #3
To sort all elements of a 2D array by row-wise.
package jex; import java.util.*; public class demo < // using bubble sort to sort 2D array // sort 2D array same as it is in a 1D array of size n * m public static void sort(int arr[][]) < int i, j,k, temp; int n=arr.length; int m=arr[0].length; for(k=0;karr[k][j+1]) < temp = arr[k][j+1]; arr[k][j+1] = arr[k][j]; arr[k][j] = temp; >> > > > public static void print(int arr[][]) < int i, j; int n=arr.length; int m=arr[0].length; for (i = 0; i < n; ++i) < for (j = 0; j < m; ++j) < System.out.print(arr[i][j]+" "); >System.out.println(); > > public static void main(String[] args) < Scanner sc=new Scanner(System.in); int[][] arr=< < 5, 12, 17, 12, 23>, < 1, 2, 4, 6, 8>, , < 3, 18, 9, 15, 25>>; System.out.println("Array Before Sorting is : "); print(arr); sort(arr); System.out.println("Array After Sorting is : "); print(arr); > >
As in the above rewrite program, the sort() method is useful to iterate each element of a 2D array and sort the array row-wise. Finally, the print method displays all the elements of the 2D array. In the main function, the 2D array is created and printed after and before calling the sort() function, as shown in the above output.
Conclusion
Sorting is a technique for arranging elements in a 2D array in a specific order. For example, in a 2D array, a cell has two indexes: its row number and its column number.
Recommended Articles
This is a guide to 2D Array Sorting in Java. Here we discuss the introduction and examples of 2D array sorting in Java, respectively. You may also have a look at the following articles to learn more –
89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8
How to sort a two-dimensional array on column values in java / How to sort a two-dimensional array in java
Sorting a one dimensional array in java is straight forward and easy, just call java.util.Arrays.sort with the array to sort as argument and you get the array sorted. But what if you want to sort a two dimensional array. There is no direct method to sort a two dimensional array in java. Just pause and think, you will surely need to think on the approach when you encounter this task for the first time.
Approach
For sorting a two dimensional array, first you need to decide on which column you have to sort or to phrase it correctly, on which array index you need to sort since a 2d array in java is an array of arrays. A 2d array in java can be visualized as :
Above array when sorted on index 0, will look like
Sorting on index 0 means that first elements of all the arrays will be compared and sorted. In terms of conventional arrays, this means that the first column elements are sorted.
Similarly, sorting on index 1 means that second elements of all the arrays will be compared and sorted. In terms of conventional arrays, this means that the elements of second column are sorted.
Finally you need to decide whether to sort elements in ascending order or descending order.
For more details on 2d array, visit How is a two dimensional array represented in java
Implementation
Since there is no straight method available in java to sort a two dimensional array, we need to develop our own implementation.
If you have noticed, there is an overloaded sort method in java.util.Arrays class which takes two arguments : the array to sort and a java.util.Comparator object.
If we pass in our own custom Comparator, it would sort the array as we require. Let’s see how.
import java.util.Arrays; import java.util.Comparator; public class PartNumberQuantityDetailer { // initialize a two dimensional array static Integer[][] itemIdAndQty = new Integer[5][2]; public static void main(String[] args) { // initialize array values itemIdAndQty[0][0] = 1234; itemIdAndQty[0][1] = 46; itemIdAndQty[1][0] = 5443; itemIdAndQty[1][1] = 564; itemIdAndQty[2][0] = 362; itemIdAndQty[2][1] = 24; itemIdAndQty[3][0] = 6742; itemIdAndQty[3][1] = 825; itemIdAndQty[4][0] = 347; itemIdAndQty[4][1] = 549; System.out.println("Before sorting"); // show the contents of array displayArray(); // sort the array on item id(first column) Arrays.sort(itemIdAndQty, new ComparatorInteger[]>() { @Override //arguments to this method represent the arrays to be sorted public int compare(Integer[] o1, Integer[] o2) { //get the item ids which are at index 0 of the array Integer itemIdOne = o1[0]; Integer itemIdTwo = o2[0]; // sort on item id return itemIdOne.compareTo(itemIdTwo); } }); // display array after sort System.out.println("After sorting on item id in ascending order"); displayArray(); // sort array on quantity(second column) Arrays.sort(itemIdAndQty, new ComparatorInteger[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { Integer quantityOne = o1[1]; Integer quantityTwo = o2[1]; // reverse sort on quantity return quantityOne.compareTo(quantityTwo); } }); // display array after sort System.out.println("After sorting on quantity in ascending order"); displayArray(); } private static void displayArray() { System.out.println("-------------------------------------"); System.out.println("Item id\t\tQuantity"); for (int i = 0; i < itemIdAndQty.length; i++) { Integer[] itemRecord = itemIdAndQty[i]; System.out.println(itemRecord[0] + "\t\t" + itemRecord[1]); } System.out.println("-------------------------------------"); } }
Before sorting
————————————-
Item id Quantity
1234 46
5443 564
362 24
6742 825
347 549
————————————-
After sorting on item id in ascending order
————————————-
Item id Quantity
347 549
362 24
1234 46
5443 564
6742 825
————————————-
After sorting on quantity in ascending order
————————————-
Item id Quantity
362 24
1234 46
347 549
5443 564
6742 825
————————————-
Explanation
A two dimensional array is created and initialized with default values. First column of the array consists of item id and second column is its quantity.
First the array is sorted on item ids(first column) and then on its quantity(second column). For sorting the array, sort method of java.util.Arrays is used which takes 2 arguments : the array to be sorted and a java.util.Comparator object.
We pass an anonymous Comparator object(anonymous object means an object which has no name and which is created at its place of use only).
As explained earlier and can be seen from Illustration 1, a 2d array in java is an array of arrays , thus, for sorting a 2d array on a column, we have to sort an integer array, therefore the generic type of this Comparator object should be Integer[ ] .
Inside Comparator object, we implement its compare method which takes two objects of Integer[ ] type. These Integer objects represent the arrays to be compared.
Since we need to compare values of first column(item ids), we retrieve the values at index 0 of the supplied Integer[ ] objects and compare them using compareTo method.
Similarly, for sorting the array on second column(quantity), the values at index 1 of the Integer[ ] objects are retrieved and compared.
Result of sorting on both columns can be seen from the output of the above program.
Let’s tweak in
- In place of using an anonymous Comparator object, a separate class which implements java.util.Comparator interface and implements its compare method can be used. In that case, instead of passing the definition of Comparator in the above program, an object of this class will be supplied.
- The above program can also be used to sort the array on column values in descending order. Just swap the caller and argument of compare method.
- The above method can also be used to sort an array of types double , String , float etc. You only need to change the generic type of Comparator according to the type of array.