# Sort the Matrix

Sort the matrix” is a standard interview problem which has been asked in many technical and algorithmic interview. Here, we are given a matrix of size N*N. Our task is to write a program to sort the given matrix such that all the elements of all rows are sorted and all the elements of all the columns are sorted.

Example:

```INPUT:
N = 3
5  1  8
2  7  9
3  6  4
OUTPUT:
1  2  3
4  5  6
7  8  9```

The steps required to sort the matrix are as follows:

1. Create an array of size N^2.
2. Copy all the elements of the matrix to the array.
3. Sort the array.
4. Copy all the elements of the array to the matrix.

#### C++ Program to sort the matrix is as follows:

```/* Program to sort the matrix */
#include<bits/stdc++.h>
using namespace std;
int main()
{
int N;
// Scan Dimensions of the matrix
cout<<"Enter the dimension of the matrix:\n";
cin>>N;

int matrix[N][N];
int temp[N*N];

// Scan Matrix Elements
cout<<"Enter the elements of the matrix:\n";
for(int i = 0 ; i < N ; i++)
for(int j = 0 ; j < N ; j++)
cin>>matrix[i][j];

// Copy all the matrix elements to the array
int k = 0;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
temp[k++] = matrix[i][j];

//Sort the matrix (in-built function)
sort(temp,temp+(N*N));

// Copy all the array elements back to matrix
k = 0;
for (int i = 0; i < N; ++i)
for (int j = 0; j < N; ++j)
matrix[i][j] = temp[k++];

//Print Sorted matrix
cout<<"The Sorted Matrix is:\n";
for(int i = 0 ; i < N ; i++)
{
for(int j = 0 ; j < N ; j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}

```
```OUTPUT:
Enter the dimension of the matrix: 3
Enter the elements of the matrix:
1 3 5
2 4 6
7 8 9
The Sorted Matrix is:
1 2 3
4 5 6
7 8 9```

Related Posts: