Given a n x n matrix. The problem is to sort the given matrix in strict order. Here strict order means that matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row āiā, where 1 <= i <= n-1, first element of row āiā is greater than or equal to the last element of row āi-1ā.
Examples:Ā
Ā
Input : mat[][] = { {5, 4, 7}, {1, 3, 8}, {2, 9, 6} } Output : 1 2 3 4 5 6 7 8 9
Ā
Approach: Create a temp[] array of size n^2. Starting with the first row one by one copy the elements of the given matrix into temp[]. Sort temp[]. Now one by one copy the elements of temp[] back to the given matrix.
Ā
Javascript
<script> Ā Ā // JavaScript implementation to sort // the given matrix Ā Ā let SIZEĀ = 10 Ā Ā // function to sort the given matrix function sortMat(mat, n) { Ā Ā Ā Ā // temporary matrix of size n^2 Ā Ā Ā Ā let temp = new Array(n * n); Ā Ā Ā Ā let k = 0; Ā Ā Ā Ā Ā Ā // copy the elements of matrix one by one Ā Ā Ā Ā // into temp[] Ā Ā Ā Ā for (let i = 0; i < n; i++) Ā Ā Ā Ā Ā Ā Ā Ā for (let j = 0; j < n; j++) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā temp[k++] = mat[i][j]; Ā Ā Ā Ā Ā Ā // sort temp[] Ā Ā Ā Ā temp.sort(); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // copy the elements of temp[] one by one Ā Ā Ā Ā // in mat[][] Ā Ā Ā Ā k = 0; Ā Ā Ā Ā for (let i = 0; i < n; i++) Ā Ā Ā Ā Ā Ā Ā Ā for (let j = 0; j < n; j++) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā mat[i][j] = temp[k++]; } Ā Ā // function to print the given matrix function printMat(mat, n) { Ā Ā Ā Ā for (let i = 0; i < n; i++) { Ā Ā Ā Ā Ā Ā Ā Ā for (let j = 0; j < n; j++) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā document.write( mat[i][j] + " " ); Ā Ā Ā Ā Ā Ā Ā Ā document.write( "<br>" ); Ā Ā Ā Ā } } Ā Ā // Driver program to test above Ā Ā Ā Ā Ā Ā let mat = [ [ 5, 4, 7 ], Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā [ 1, 3, 8 ], Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā [ 2, 9, 6 ] ]; Ā Ā Ā Ā let n = 3; Ā Ā Ā Ā Ā Ā document.write( "Original Matrix: " + "<br>" ); Ā Ā Ā Ā printMat(mat, n); Ā Ā Ā Ā Ā Ā sortMat(mat, n); Ā Ā Ā Ā document.write( "<br>" ); Ā Ā Ā Ā document.write( " Matrix After Sorting: " + "<br>" ); Ā Ā Ā Ā printMat(mat, n); Ā Ā // This code is contributed by Manoj Ā Ā </script> |
Output:Ā Ā
Original Matrix: 5 4 7 1 3 8 2 9 6 Matrix After Sorting: 1 2 3 4 5 6 7 8 9
Time Complexity: O(n2log2n).Ā
Auxiliary Space: O(n2).
Ā
Please refer complete article on Sort the given matrix for more details!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!