# Sorting rows of matrix in ascending order followed by columns in descending order

Last Updated : 19 Aug, 2022

Given a matrix, sort the rows of matrix in ascending order followed by sorting the columns in descending order.
Examples :

```Input : a[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
Output : 7 8 9
4 5 6
1 2 3

Input : a[3][3] = {{3, 2, 1},
{9, 8, 7},
{6, 5, 4}};
Output : 7 8 9
4 5 6
1 2 3```

Approach:

• Traverse all rows one by one and sort rows in ascending order using a simple array sort.
• Convert matrix to its transpose
• Again sort all rows, but this time in descending order.
• Again convert a matrix to its transpose

Below is the implementation of the above approach:

## C++

 `// C++ implementation to sort the rows` `// of matrix in ascending order followed by` `// sorting the columns in descending order` `#include ` `using` `namespace` `std;`   `#define MAX_SIZE 10`   `// function to sort each row of the matrix` `// according to the order specified by ` `// ascending.` `void` `sortByRow(``int` `mat[][MAX_SIZE], ``int` `n, ` `                           ``bool` `ascending)` `{` `    ``for` `(``int` `i = 0; i < n; i++)` `    ``{` `      ``if` `(ascending)    ` `        ``sort(mat[i], mat[i] + n);` `      ``else` `          ``sort(mat[i], mat[i] + n, greater<``int``>());` `    ``}      ` `}`   `// function to find transpose of the matrix` `void` `transpose(``int` `mat[][MAX_SIZE], ``int` `n)` `{` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``for` `(``int` `j = i + 1; j < n; j++) `   `            ``// swapping element at index (i, j) ` `            ``// by element at index (j, i)` `            ``swap(mat[i][j], mat[j][i]);` `}`   `// function to sort the matrix row-wise` `// and column-wise` `void` `sortMatRowAndColWise(``int` `mat[][MAX_SIZE],` `                                       ``int` `n)` `{` `    ``// sort rows of mat[][]` `    ``sortByRow(mat, n, ``true``);`   `    ``// get transpose of mat[][]` `    ``transpose(mat, n);`   `    ``// again sort rows of mat[][] in descending` `    ``// order.` `    ``sortByRow(mat, n, ``false``);`   `    ``// again get transpose of mat[][]` `    ``transpose(mat, n);` `}`   `// function to print the matrix` `void` `printMat(``int` `mat[][MAX_SIZE], ``int` `n)` `{` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``for` `(``int` `j = 0; j < n; j++)` `            ``cout << mat[i][j] << ``" "``;` `        ``cout << endl;` `    ``}` `}`   `// Driver program to test above` `int` `main()` `{` `    ``int` `n = 3;` `    `  `    ``int` `mat[n][MAX_SIZE]  = {{3, 2, 1},` `                            ``{9, 8, 7}, ` `                            ``{6, 5, 4}};`   `    ``cout << ``"Original Matrix:\n"``;` `    ``printMat(mat, n);`   `    ``sortMatRowAndColWise(mat, n);`   `    ``cout << ``"\nMatrix After Sorting:\n"``;` `    ``printMat(mat, n);`   `    ``return` `0;` `}`

## Java

 `// Java implementation to sort the rows` `// of matrix in ascending order followed by` `// sorting the columns in descending order` `import` `java.util.Arrays;` `import` `java.util.Collections;`   `class` `GFG` `{` `    ``static` `int` `MAX_SIZE=``10``;` `    `  `    ``// function to sort each row of the matrix` `    ``// according to the order specified by ` `    ``// ascending.` `    ``static` `void` `sortByRow(Integer mat[][], ``int` `n, ` `                                 ``boolean` `ascending)` `    ``{` `        ``for` `(``int` `i = ``0``; i < n; i++)` `        ``{` `            ``if` `(ascending) ` `                ``Arrays.sort(mat[i]);` `            ``else` `                ``Arrays.sort(mat[i],Collections.reverseOrder());` `        ``}     ` `    ``}` `    `  `    ``// function to find transpose of the matrix` `    ``static` `void` `transpose(Integer mat[][], ``int` `n)` `    ``{` `        ``for` `(``int` `i = ``0``; i < n; i++)` `            ``for` `(``int` `j = i + ``1``; j < n; j++) ` `            ``{` `                ``// swapping element at index (i, j) ` `                ``// by element at index (j, i)` `                ``int` `temp = mat[i][j];` `                ``mat[i][j] = mat[j][i];` `                ``mat[j][i] = temp;` `            ``}` `    ``}` `    `  `    ``// function to sort the matrix row-wise` `    ``// and column-wise` `    ``static` `void` `sortMatRowAndColWise(Integer mat[][],` `                                              ``int` `n)` `    ``{` `        ``// sort rows of mat[][]` `        ``sortByRow(mat, n, ``true``);` `    `  `        ``// get transpose of mat[][]` `        ``transpose(mat, n);` `    `  `        ``// again sort rows of mat[][] in descending` `        ``// order.` `        ``sortByRow(mat, n, ``false``);` `    `  `        ``// again get transpose of mat[][]` `        ``transpose(mat, n);` `    ``}` `    `  `    ``// function to print the matrix` `    ``static` `void` `printMat(Integer mat[][], ``int` `n)` `    ``{` `        ``for` `(``int` `i = ``0``; i < n; i++) ` `        ``{` `            ``for` `(``int` `j = ``0``; j < n; j++)` `                ``System.out.print(mat[i][j] + ``" "``);` `            ``System.out.println();` `        ``}` `    ``}` `    `  `    ``// Driver code` `    ``public` `static` `void` `main (String[] args) ` `    ``{` `        ``int` `n = ``3``;` `        `  `        ``Integer mat[][] = {{``3``, ``2``, ``1``},` `                           ``{``9``, ``8``, ``7``}, ` `                           ``{``6``, ``5``, ``4``}};` `    `  `        ``System.out.print(``"Original Matrix:\n"``);` `        ``printMat(mat, n);` `    `  `        ``sortMatRowAndColWise(mat, n);` `    `  `        ``System.out.print(``"\nMatrix After Sorting:\n"``);` `        ``printMat(mat, n);` `    ``}` `}`   `// This code is contributed by Anant Agarwal.`

## Python3

 `# Python implementation to sort the rows` `# of matrix in ascending order followed by` `# sorting the columns in descending order`   `MAX_SIZE``=``10` ` `  `# function to sort each row of the matrix` `# according to the order specified by ` `# ascending.` `def` `sortByRow(mat, n, ascending):`   `    ``for` `i ``in` `range``(n):` `        ``if` `(ascending):    ` `            ``mat[i].sort()` `        ``else``:` `            ``mat[i].sort(reverse``=``True``)` ` `  `# function to find ` `# transpose of the matrix` `def` `transpose(mat, n):`   `    ``for` `i ``in` `range``(n):` `        ``for` `j ``in` `range``(i ``+` `1``, n): ` `        `  `            ``# swapping element at index (i, j) ` `            ``# by element at index (j, i)` `            ``temp ``=` `mat[i][j]` `            ``mat[i][j] ``=` `mat[j][i]` `            ``mat[j][i] ``=` `temp`   `# function to sort ` `# the matrix row-wise` `# and column-wise` `def` `sortMatRowAndColWise(mat, n):`   `    ``# sort rows of mat[][]` `    ``sortByRow(mat, n, ``True``)` ` `  `    ``# get transpose of mat[][]` `    ``transpose(mat, n)` ` `  `    ``# again sort rows of ` `    ``# mat[][] in descending` `    ``# order.` `    ``sortByRow(mat, n, ``False``)` ` `  `    ``# again get transpose of mat[][]` `    ``transpose(mat, n)` ` `  `# function to print the matrix` `def` `printMat(mat, n):`   `    ``for` `i ``in` `range``(n):` `        ``for` `j ``in` `range``(n):` `            ``print``(mat[i][j] , ``" "``, end``=``"")` `        ``print``()`   `#Driver code` `n ``=` `3` `     `  `mat ``=` `[[``3``, ``2``, ``1``],` `    ``[``9``, ``8``, ``7``], ` `    ``[``6``, ``5``, ``4``]]` ` `  `print``(``"Original Matrix:"``)` `printMat(mat, n)` ` `  `sortMatRowAndColWise(mat, n)` ` `  `print``(``"Matrix After Sorting:"``)` `printMat(mat, n)`   `# This code is contributed` `# by Anant Agarwal.`

## C#

 `// C# implementation to sort the rows` `// of matrix in ascending order followed by` `// sorting the columns in descending order` `using` `System;`   `public` `static` `class` `GFG {` `    `  `    ``// function to sort each row of the matrix` `    ``// according to the order specified by` `    ``// ascending.` `    ``static` `void` `sortByRow(``int``[, ] m)` `    ``{` `        ``// loop for rows of matrix` `        ``for` `(``int` `i = 0; i < m.GetLength(0); i++) {`   `            ``// loop for column of matrix` `            ``for` `(``int` `j = 0; j < m.GetLength(1); j++) {`   `                ``// loop for comparison and swapping` `                ``for` `(``int` `k = 0; k < m.GetLength(1) - j - 1;` `                     ``k++) {` `                    ``if` `(m[i, k] > m[i, k + 1]) {`   `                        ``// swapping of elements` `                        ``int` `t = m[i, k];` `                        ``m[i, k] = m[i, k + 1];` `                        ``m[i, k + 1] = t;` `                    ``}` `                ``}` `            ``}` `        ``}` `    ``}`   `    ``static` `void` `reverseArray(``int``[, ] arr)` `    ``{`   `        ``// Traverse each row of [,]arr` `        ``for` `(``int` `i = 0; i < arr.GetLength(1); i++) {`   `            ``// Initialise start and end index` `            ``int` `start = 0;` `            ``int` `end = arr.GetLength(0) - 1;`   `            ``// Till start < end, swap the element` `            ``// at start and end index` `            ``while` `(start < end) {`   `                ``// Swap the element` `                ``int` `temp = arr[i, start];` `                ``arr[i, start] = arr[i, end];` `                ``arr[i, end] = temp;`   `                ``// Increment start and decrement` `                ``// end for next pair of swapping` `                ``start++;` `                ``end--;` `            ``}` `        ``}` `    ``}`   `    ``// function to find transpose of the matrix` `    ``public` `static` `void` `transpose(``int``[, ] mat, ``int` `n)` `    ``{` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``for` `(``int` `j = i + 1; j < n; j++) {`   `                ``// swapping element at index (i, j)` `                ``// by element at index (j, i)` `                ``int` `temp = mat[i, j];` `                ``mat[i, j] = mat[j, i];` `                ``mat[j, i] = temp;` `            ``}` `        ``}` `    ``}`   `    ``// function to sort the matrix row-wise` `    ``// and column-wise` `    ``public` `static` `void` `sortMatRowAndColWise(``int``[, ] mat,` `                                            ``int` `n)` `    ``{` `        ``// sort rows of mat[][]` `        ``sortByRow(mat);`   `        ``// get transpose of mat[][]` `        ``transpose(mat, n);`   `        ``// again sort rows of mat[][] in descending` `        ``// order.` `        ``sortByRow(mat);` `        ``reverseArray(mat);`   `        ``// again get transpose of mat[][]` `        ``transpose(mat, n);` `    ``}`   `    ``// function to print the matrix` `    ``public` `static` `void` `printMat(``int``[, ] mat, ``int` `n)` `    ``{` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``for` `(``int` `j = 0; j < n; j++) {` `                ``Console.Write(mat[i, j]);` `                ``Console.Write(``" "``);` `            ``}` `            ``Console.Write(``"\n"``);` `        ``}` `    ``}`   `    ``// Driver program to test above` `    ``internal` `static` `void` `Main()` `    ``{` `        ``int` `n = 3;`   `        ``int``[, ] mat` `            ``= { { 3, 2, 1 }, { 9, 8, 7 }, { 6, 5, 4 } };`   `        ``Console.Write(``"Original Matrix:\n"``);` `        ``printMat(mat, n);`   `        ``sortMatRowAndColWise(mat, n);`   `        ``Console.Write(``"\nMatrix After Sorting:\n"``);` `        ``printMat(mat, n);` `    ``}` `}`   `// This code is contributed by Aarti_Rathi`

## PHP

 ``

## Javascript

 ``

Output

```Original Matrix:
3 2 1
9 8 7
6 5 4

Matrix After Sorting:
7 8 9
4 5 6
1 2 3 ```

Time Complexity: O(N2 log N)
Auxiliary Space: O(1), since no extra space has been taken.

Previous
Next