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:

  1. Program to Add two Matrix.
  2. Program to Transpose a Matrix.
  3. Program to Multiply Two Matrix.
  4. Program to check Identity Matrix.
  5. Program to check Idempotent Matrix.
  6. Program to check Involuntary Matrix.
  7. Program to print matrix in zig-zag order.
  8. Program to print matrix in spiral order.
  9. Program to count total number of words in a string.
  10. Program to find smallest and largest word of the String.
  11. Program to find Most Frequent Character of the String.
  12. Program to Remove all the blank spaces from the String.
  13. Program to check if String is isogram or not.
  14. Program to Reverse Each word of the String.
  15. Program to Print All the Substring of the Given String.
  16. Program to find longest palindromic Substring.
  17. Program to check Anagram Strings.
  18. Program to check whether two Strings are Rotation of each other or not.
  19. Find Most Frequent Element of the Array.
  20. Find Pair in an Array with Given Sum.

You may also like...