Sort the matrix column-wise

04 Jul, 2022
Given a matrix mat[][] of dimensions N * M, the task is to sort each column of a matrix in ascending order and print the updated matrix.
Examples:
Input: mat[][] = { {1, 6, 10}, {8, 5, 9}, {9, 4, 15}, {7, 3, 60} }Output:1 3 97 4 108 5 159 6 60Explanation:The input matrix is sorted in a column wise manner,  1 < 7 < 8 < 93 < 4 < 5 < 69 < 10 < 15 < 60
Input: arr[][] = { {1, 6}, {8, 4}, {9, 7} }Output:1 48 69 7
Approach: Follow the steps below to solve the problem:
Traverse the matrix
Find the transpose of the given matrix mat[][].
Store this transpose of mat[][] in a 2D vector, tr[][]
Traverse the rows of the matrix tr[][]
Sort each row of the matrix using the sort function.
Store the transpose of tr[][] in mat[][]
Print the matrix, mat[][]
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the transpose// of the matrix mat[]vector<vector<int> > transpose(    vector<vector<int> > mat,    int row, int col){     // Stores the transpose    // of matrix mat[][]    vector<vector<int> > tr(        col, vector<int>(row));     // Traverse each row of the matrix    for (int i = 0; i < row; i++) {         // Traverse each column of the matrix        for (int j = 0; j < col; j++) {             // Transpose matrix elements            tr[j][i] = mat[i][j];        }    }     return tr;} // Function to sort the given// matrix in row wise mannervoid RowWiseSort(vector<vector<int> >& B){    // Traverse the row    for (int i = 0; i < (int)B.size(); i++) {         // Row - Wise Sorting        sort(B[i].begin(), B[i].end());    }} // Function to print the matrix// in column wise sorted mannervoid sortCol(vector<vector<int> > mat,             int N, int M){    // Function call to find transpose    // of the matrix mat[][]    vector<vector<int> > B        = transpose(mat, N, M);     // Sorting the matrix row-wise    RowWiseSort(B);     // Calculate transpose of B[][]    mat = transpose(B, M, N);     // Print the matrix mat[][]    for (int i = 0; i < N; i++) {        for (int j = 0; j < M; j++) {             cout << mat[i][j] << " ";        }        cout << '\n';    }} // Driver Codeint main(){    // Input    vector<vector<int> > mat = { { 1, 6, 10 },                                 { 8, 5, 9 },                                 { 9, 4, 15 },                                 { 7, 3, 60 } };     int N = mat.size();    int M = mat[0].size();     // Function call to print the matrix    // in column wise sorted manner    sortCol(mat, N, M);     return 0;}
// Java program for the above approachimport java.util.*;import java.util.Arrays; class GFG{ // Function to find the transpose// of the matrix mat[]static int[][] transpose(int[][] mat, int row,                         int col){         // Stores the transpose    // of matrix mat[][]    int[][] tr = new int[col][row];     // Traverse each row of the matrix    for(int i = 0; i < row; i++)    {                 // Traverse each column of the matrix        for(int j = 0; j < col; j++)        {                         // Transpose matrix elements            tr[j][i] = mat[i][j];        }    }    return tr;} // Function to sort the given// matrix in row wise mannerstatic void RowWiseSort(int[][] B){         // Traverse the row    for(int i = 0; i < (int)B.length; i++)    {                 // Row - Wise Sorting        Arrays.sort(B[i]);    }} // Function to print the matrix// in column wise sorted mannerstatic void sortCol(int[][] mat, int N, int M){         // Function call to find transpose    // of the matrix mat[][]    int[][] B = transpose(mat, N, M);     // Sorting the matrix row-wise    RowWiseSort(B);     // Calculate transpose of B[][]    mat = transpose(B, M, N);     // Print the matrix mat[][]    for(int i = 0; i < N; i++)    {        for(int j = 0; j < M; j++)        {            System.out.print(mat[i][j] + " ");        }        System.out.println();    }} // Driver Codepublic static void main(String[] args){         // Input    int[][] mat = { { 1, 6, 10 },                    { 8, 5, 9 },                    { 9, 4, 15 },                    { 7, 3, 60 } };     int N = mat.length;    int M = mat[0].length;     // Function call to print the matrix    // in column wise sorted manner    sortCol(mat, N, M);}} // This code is contributed by ukasp
# Python3 program for the above approach # Function to find the transpose# of the matrix mat[]def transpose(mat, row, col):     # Stores the transpose    # of matrix mat[][]    tr = [[0 for i in range(row)] for i in range(col)]     # Traverse each row of the matrix    for i in range(row):         # Traverse each column of the matrix        for j in range(col):             # Transpose matrix elements            tr[j][i] = mat[i][j]    return tr # Function to sort the given# matrix in row wise mannerdef RowWiseSort(B):       # Traverse the row    for i in range(len(B)):               # Row - Wise Sorting        B[i] = sorted(B[i])    return B # Function to print the matrix# in column wise sorted mannerdef sortCol(mat, N, M):       # Function call to find transpose    # of the matrix mat[][]    B = transpose(mat, N, M)     # Sorting the matrix row-wise    B = RowWiseSort(B)     # Calculate transpose of B[][]    mat = transpose(B, M, N)     # Print the matrix mat[][]    for i in range(N):        for j in range(M):            print(mat[i][j], end = " ")        print() # Driver Codeif __name__ == '__main__':       # Input    mat =[ [1, 6, 10 ],            [ 8, 5, 9 ],            [ 9, 4, 15 ],            [ 7, 3, 60 ] ]     N = len(mat)    M = len(mat[0])     # Function call to print the matrix    # in column wise sorted manner    sortCol(mat, N, M) # This code is contributed by mohit kumar 29.
<script> // JavaScript program for the above approach // Function to find the transpose// of the matrix mat[]function transpose(mat,row,col){    // Stores the transpose    // of matrix mat[][]    let tr = new Array(col);    for(let i=0;i<col;i++)    {        tr[i]=new Array(row);    }      // Traverse each row of the matrix    for(let i = 0; i < row; i++)    {                           // Traverse each column of the matrix        for(let j = 0; j < col; j++)        {                          // Transpose matrix elements            tr[j][i] = mat[i][j];        }    }    return tr;} // Function to sort the given// matrix in row wise mannerfunction RowWiseSort(B){    // Traverse the row    for(let i = 0; i < B.length; i++)    {                  // Row - Wise Sorting        (B[i]).sort(function(a,b){return a-b;});    }} // Function to print the matrix// in column wise sorted mannerfunction sortCol(mat,n,M){    // Function call to find transpose    // of the matrix mat[][]    let B = transpose(mat, N, M);      // Sorting the matrix row-wise    RowWiseSort(B);      // Calculate transpose of B[][]    mat = transpose(B, M, N);      // Print the matrix mat[][]    for(let i = 0; i < N; i++)    {        for(let j = 0; j < M; j++)        {            document.write(mat[i][j] + " ");        }        document.write("<br>");    }} // Driver Codelet mat = [[ 1, 6, 10 ],                    [ 8, 5, 9 ],                    [ 9, 4, 15 ],                    [ 7, 3, 60 ] ];  let N = mat.length;let M = mat[0].length; // Function call to print the matrix// in column wise sorted mannersortCol(mat, N, M);  // This code is contributed by avanitrachhadiya2155 </script>
1 3 9 
7 4 10 
8 5 15 
9 6 60
 
Time Complexity: O(N * M)Auxiliary Space: O(N * M)
 
mohit kumar 29
ukasp
nidhi_biet
avanitrachhadiya2155
simmytarika5
array-rearrange
Mathematical
Matrix
Sorting
Mathematical
Sorting
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Segment Tree | Set 1 (Sum of given range)
Check if a number is Palindrome
Print a given matrix in spiral form
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7