We are given a 2D array of order N X M and a column number K ( 1<=K<=m). Our task is to sort the 2D array according to values in Column K.
Examples:
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 65
Sorting it by values in column 3
Output : 39 27 11 42
24 64 20 65
54 78 56 89
10 93 91 90
Java
import java.io.*;
import java.util.*;
class GFG {
public static void sortbyColumn( int arr[][], int col)
{
Arrays.sort(arr, (a, b) -> Integer.compare(a[col],b[col]));
}
public static void main(String args[])
{
int matrix[][] = { { 39 , 27 , 11 , 42 },
{ 10 , 93 , 91 , 90 },
{ 54 , 78 , 56 , 89 },
{ 24 , 64 , 20 , 65 } };
int col = 3 ;
sortbyColumn(matrix, col - 1 );
for ( int i = 0 ; i < matrix.length; i++) {
for ( int j = 0 ; j < matrix[i].length; j++)
System.out.print(matrix[i][j] + " " );
System.out.println();
}
}
}
|
Output
39 27 11 42
24 64 20 65
54 78 56 89
10 93 91 90
The idea is to use Arrays.sort in Java
Java
import java.util.*;
class sort2DMatrixbycolumn {
public static void sortbyColumn( int arr[][], int col)
{
Arrays.sort(arr, new Comparator< int []>() {
@Override
public int compare( final int [] entry1,
final int [] entry2)
{
if (entry1[col] > entry2[col])
return 1 ;
else
return - 1 ;
}
});
}
public static void main(String args[])
{
int matrix[][] = { { 39 , 27 , 11 , 42 },
{ 10 , 93 , 91 , 90 },
{ 54 , 78 , 56 , 89 },
{ 24 , 64 , 20 , 65 } };
int col = 3 ;
sortbyColumn(matrix, col - 1 );
for ( int i = 0 ; i < matrix.length; i++) {
for ( int j = 0 ; j < matrix[i].length; j++)
System.out.print(matrix[i][j] + " " );
System.out.println();
}
}
}
|
Output
39 27 11 42
24 64 20 65
54 78 56 89
10 93 91 90
Time complexity: O(n log n) where n is the number of rows.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
15 May, 2023
Like Article
Save Article