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:
- Create an array of size N^2.
- Copy all the elements of the matrix to the array.
- Sort the array.
- 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:
- Program to Add two Matrix.
- Program to Transpose a Matrix.
- Program to Multiply Two Matrix.
- Program to check Identity Matrix.
- Program to check Idempotent Matrix.
- Program to check Involuntary Matrix.
- Program to print matrix in zig-zag order.
- Program to print matrix in spiral order.
- Program to count total number of words in a string.
- Program to find smallest and largest word of the String.
- Program to find Most Frequent Character of the String.
- Program to Remove all the blank spaces from the String.
- Program to check if String is isogram or not.
- Program to Reverse Each word of the String.
- Program to Print All the Substring of the Given String.
- Program to find longest palindromic Substring.
- Program to check Anagram Strings.
- Program to check whether two Strings are Rotation of each other or not.
- Find Most Frequent Element of the Array.
- Find Pair in an Array with Given Sum.