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.
Ā
Java
// Java implementation toĀ // sort the given matrix import java.io.*; import java.util.*; Ā Ā class GFG { Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā static int SIZE = 10 ; Ā Ā Ā Ā Ā Ā // function to sort the given matrix Ā Ā Ā Ā static void sortMat( int mat[][], int n) Ā Ā Ā Ā { Ā Ā Ā Ā Ā Ā Ā Ā // temporary matrix of size n^2 Ā Ā Ā Ā Ā Ā Ā Ā int temp[] = new int [n * n]; Ā Ā Ā Ā Ā Ā Ā Ā int k = 0 ; Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // copy the elements of matrixĀ Ā Ā Ā Ā Ā Ā Ā Ā // one by one into temp[] Ā Ā Ā Ā Ā Ā Ā Ā for ( int i = 0 ; i < n; i++) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for ( int j = 0 ; j < n; j++) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā temp[k++] = mat[i][j]; Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // sort temp[] Ā Ā Ā Ā Ā Ā Ā Ā Arrays.sort(temp); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // copy the elements of temp[] Ā Ā Ā Ā Ā Ā Ā Ā // one by one in mat[][] Ā Ā Ā Ā Ā Ā Ā Ā k = 0 ; Ā Ā Ā Ā Ā Ā Ā Ā for ( int i = 0 ; i < n; i++) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for ( int j = 0 ; j < n; j++) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā mat[i][j] = temp[k++]; Ā Ā Ā Ā } Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā // function to print the given matrix Ā Ā Ā Ā static void printMat( int 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 program to test above Ā Ā Ā Ā public static void main(String args[]) Ā Ā Ā Ā { Ā Ā Ā Ā Ā Ā Ā Ā int mat[][] = { { 5 , 4 , 7 }, Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā { 1 , 3 , 8 }, Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā { 2 , 9 , 6 } }; Ā Ā Ā Ā Ā Ā Ā Ā int n = 3 ; Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā System.out.println( "Original Matrix:" ); Ā Ā Ā Ā Ā Ā Ā Ā printMat(mat, n); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā sortMat(mat, n); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā System.out.println( "Matrix After Sorting:" ); Ā Ā Ā Ā Ā Ā Ā Ā printMat(mat, n); Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā } } Ā Ā // This code is contributed by Nikita Tiwari. |
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!