VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-matrix-way-increasing-order/

⇱ Sort a Matrix in all way increasing order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort a Matrix in all way increasing order

Last Updated : 13 Sep, 2023

Given a square matrix of order N*N having distinct elements, the task is to sort given matrix in such a way that its rows, columns and both diagonals (diagonal and anti-diagonal) are in increasing order.

Examples: 

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

Input : arr[2][2] = {0, 4,
 5, 2} 
Output :{0, 2,
 4, 5}

Sorting any matrix in a way that its rows, columns and main diagonal are in increasing order is easy. If we consider matrix elements in sequence according to row-major order and sort the sequence, we get the desired result.

Example: arr[2][2] : {1, 2
 3, 4}
Rows in increasing order: {1,2} and {3,4}
Columns in increasing order: {1,3} and {2,4}
Diagonal in increasing order: {1,4}
Anti-diagonal in increasing order: {2,3}

Implementation:


Output
0 1 2 
3 4 5 
6 8 9 

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

Comment
Article Tags:
Article Tags: