Wednesday, July 3, 2024
HomeLanguagesJavaSorting a 2D Array according to values in any given column in...

Sorting a 2D Array according to values in any given column in Java

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




// Java Program to Sorting a 2D Array according to values
// in any given column
 
import java.io.*;
import java.util.*;
 
// Class
class GFG {
   
    // Method to sort by column
    public static void sortbyColumn(int arr[][], int col)
    {
        // Using built-in sort function Arrays.sort with lambda expressions
       
      Arrays.sort(arr, (a, b) -> Integer.compare(a[col],b[col])); // increasing order
         
    }
    public static void main(String args[])
    {
        int matrix[][] = { { 39, 27, 11, 42 },
                           { 10, 93, 91, 90 },
                           { 54, 78, 56, 89 },
                           { 24, 64, 20, 65 } };
        // Sort this matrix by 3rd Column
        int col = 3;
        sortbyColumn(matrix, col - 1);
   
        // Display the sorted Matrix
        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




// Java Code to sort 2D Matrix
// according to any Column
 
// Importing required classes
import java.util.*;
class sort2DMatrixbycolumn {
 
    // Function to sort by column
    public static void sortbyColumn(int arr[][], int col)
    {
        // Using built-in sort function Arrays.sort
        Arrays.sort(arr, new Comparator<int[]>() {
            @Override
            // Compare values according to columns
            public int compare(final int[] entry1,
                               final int[] entry2)
            {
 
                // To sort in descending order revert
                // the '>' Operator
                if (entry1[col] > entry2[col])
                    return 1;
                else
                    return -1;
            }
        }); // End of function call sort().
    }
 
    // Main driver method
    public static void main(String args[])
    {
        int matrix[][] = { { 39, 27, 11, 42 },
                           { 10, 93, 91, 90 },
                           { 54, 78, 56, 89 },
                           { 24, 64, 20, 65 } };
 
        // Sorting the matrix by 3rd Column
        int col = 3;
        sortbyColumn(matrix, col - 1);
 
        // Printing the sorted matrix
        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.

This article is contributed by DANISH KALEEM. If you like Lazyroar and would like to contribute, you can also write an article using write.neveropen.co.za or mail your article to review-team@neveropen.co.za. See your article appearing on the Lazyroar 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.

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments