A 2D array can be sorted based on the values of any selected column. Java provides Arrays.sort() with a comparator, which allows us to compare rows using the value at the required column.
Illustration:
Input: If our 2D array is given as (Order 4X4)
39 27 11 42
10 93 91 90
54 78 56 89
24 64 20 65Sorting it by values in column 3
Output:
39 27 11 42
24 64 20 65
54 78 56 89
10 93 91 90
Approach
- Select the column according to which the rows should be sorted.
- Use Arrays.sort() with a comparator.
- Compare the values of the selected column in each row.
- The complete rows are rearranged based on those values.
import java.io.*;
import java.util.*;
class GFG {
public static void sortbyColumn(int a[][], int c){
Arrays.sort(a, (x, y) -> Integer.compare(x[c],y[c]));
}
public static void main(String args[])
{
int m[][] = { { 39, 27, 11, 42 },
{ 10, 93, 91, 90 },
{ 54, 78, 56, 89 },
{ 24, 64, 20, 65 } };
// Sort this matrix by 3rd Column
int c = 3;
sortbyColumn(m, c - 1);
// Display the sorted Matrix
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}
Output
39 27 11 42 24 64 20 65 54 78 56 89 10 93 91 90
Explanation
- column = 2 represents the 3rd column because array indexing starts from 0.
- a[column] and b[column] are compared for two rows.
- Integer.compare() sorts the rows in ascending order.
- The entire row moves together; only the sorting order changes.