C++ Program to Sort the given matrix
Last Updated :
18 Jan, 2022
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.
Â
C++
#include <bits/stdc++.h>
using namespace std;
#define SIZE 10
void sortMat( int mat[SIZE][SIZE], int n)
{
int temp[n * n];
int k = 0;
for ( int i = 0; i < n; i++)
for ( int j = 0; j < n; j++)
temp[k++] = mat[i][j];
sort(temp, temp + k);
k = 0;
for ( int i = 0; i < n; i++)
for ( int j = 0; j < n; j++)
mat[i][j] = temp[k++];
}
void printMat( int mat[SIZE][SIZE], int n)
{
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++)
cout << mat[i][j] << " " ;
cout << endl;
}
}
int main()
{
int mat[SIZE][SIZE] = { { 5, 4, 7 },
{ 1, 3, 8 },
{ 2, 9, 6 } };
int n = 3;
cout << "Original Matrix:
";
printMat(mat, n);
sortMat(mat, n);
cout << "
Matrix After Sorting:
";
printMat(mat, n);
return 0;
}
|
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!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...