VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sorting-rows-matrix-ascending-order-followed-sorting-columns-descending-order/

⇱ Sorting rows of matrix in ascending order followed by columns in descending order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:


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.

Comment
Article Tags:
Article Tags: