Flatten and Sort - O(n ^ 2 log n) Time and O(n ^ 2) Space
The idea is to flatten the given matrix into a 1-dimensional vector and sort all its elements. After sorting, place the elements back into the matrix row by row.
Let us understand with example: Input: mat[][] = [[1, 5, 3], [2, 8, 7], [4, 6, 9]]
Flatten the matrix into a vector v = [1, 5, 3, 2, 8, 7, 4, 6, 9].
Sort the vector to get v = [1, 2, 3, 4, 5, 6, 7, 8, 9].
Start filling the matrix row by row using the sorted elements from v.
The first row becomes [1, 2, 3], the second row becomes [4, 5, 6], and the third row becomes [7, 8, 9].
The final sorted matrix is [[1, 2, 3], [4, 5, 6], [7, 8, 9]].
C++
#include<bits/stdc++.h>usingnamespacestd;// Function to sort the matrix in non-decreasing order.vector<vector<int>>sortedMatrix(vector<vector<int>>mat){intn=mat.size();vector<int>v;// Flattening the matrix into a 1-dimensional vector.for(inti=0;i<n;i++)for(intj=0;j<n;j++)v.push_back(mat[i][j]);// Sorting the vector in non-decreasing order.sort(v.begin(),v.end());intc=0;// Reshaping the 1-dimensional vector back into the matrix.for(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i][j]=v[c++];// Returning the sorted matrix.returnmat;}intmain(){vector<vector<int>>mat={{1,5,3},{2,8,7},{4,6,9}};vector<vector<int>>res=sortedMatrix(mat);cout<<"[";for(inti=0;i<res.size();i++){cout<<"[";for(intj=0;j<res[i].size();j++){cout<<res[i][j];if(j!=res[i].size()-1)cout<<", ";}cout<<"]";if(i!=res.size()-1)cout<<",\n ";}cout<<"]\n";return0;}
Java
importjava.util.ArrayList;importjava.util.Arrays;importjava.util.Collections;// Function to sort the matrix in non-decreasing order.publicclassGFG{publicstaticint[][]sortedMatrix(int[][]mat){intn=mat.length;ArrayList<Integer>v=newArrayList<>();// Flattening the matrix into a 1-dimensional// vector.for(inti=0;i<n;i++)for(intj=0;j<n;j++)v.add(mat[i][j]);// Sorting the vector in non-decreasing order.Collections.sort(v);intc=0;// Reshaping the 1-dimensional vector back into the// matrix.for(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i][j]=v.get(c++);// Returning the sorted matrix.returnmat;}publicstaticvoidmain(String[]args){int[][]mat={{1,5,3},{2,8,7},{4,6,9}};int[][]res=sortedMatrix(mat);System.out.print("[");for(inti=0;i<res.length;i++){System.out.print("[");for(intj=0;j<res[i].length;j++){System.out.print(res[i][j]);if(j!=res[i].length-1)System.out.print(", ");}System.out.print("]");if(i!=res.length-1)System.out.print(",\n ");}System.out.print("]\n");}}
Python
defsortedMatrix(mat):n=len(mat)v=[]# Flattening the matrix into a 1-dimensional vector.foriinrange(n):forjinrange(n):v.append(mat[i][j])# Sorting the vector in non-decreasing order.v.sort()c=0# Reshaping the 1-dimensional vector back into the matrix.foriinrange(n):forjinrange(n):mat[i][j]=v[c]c+=1# Returning the sorted matrix.returnmatif__name__=="__main__":mat=[[1,5,3],[2,8,7],[4,6,9]]res=sortedMatrix(mat)print("[")foriinrange(len(res)):print("[",end="")forjinrange(len(res[i])):print(res[i][j],end="")ifj!=len(res[i])-1:print(", ",end="")print("]")ifi!=len(res)-1:print(",\n ",end="")print("]\n")
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;// Function to sort the matrix in non-decreasing order.publicclassGFG{publicstaticint[][]sortedMatrix(int[][]mat){intn=mat.Length;List<int>v=newList<int>();// Flattening the matrix into a 1-dimensional// vector.for(inti=0;i<n;i++)for(intj=0;j<n;j++)v.Add(mat[i][j]);// Sorting the vector in non-decreasing order.v.Sort();intc=0;// Reshaping the 1-dimensional vector back into the// matrix.for(inti=0;i<n;i++)for(intj=0;j<n;j++)mat[i][j]=v[c++];// Returning the sorted matrix.returnmat;}publicstaticvoidMain(){int[][]mat=newint[][]{newint[]{1,5,3},newint[]{2,8,7},newint[]{4,6,9}};int[][]res=sortedMatrix(mat);Console.Write("[");for(inti=0;i<res.Length;i++){Console.Write("[");for(intj=0;j<res[i].Length;j++){Console.Write(res[i][j]);if(j!=res[i].Length-1)Console.Write(", ");}Console.Write("]");if(i!=res.Length-1)Console.Write(",\n ");}Console.Write("]\n");}}
JavaScript
// Function to sort the matrix in non-decreasing order.functionsortedMatrix(mat){letn=mat.length;letv=[];// Flattening the matrix into a 1-dimensional vector.for(leti=0;i<n;i++)for(letj=0;j<n;j++)v.push(mat[i][j]);// Sorting the vector in non-decreasing order.v.sort((a,b)=>a-b);letc=0;// Reshaping the 1-dimensional vector back into the// matrix.for(leti=0;i<n;i++)for(letj=0;j<n;j++)mat[i][j]=v[c++];// Returning the sorted matrix.returnmat;}// Driver codeletmat=[[1,5,3],[2,8,7],[4,6,9]];letres=sortedMatrix(mat);console.log("[");for(leti=0;i<res.length;i++){console.log("[");for(letj=0;j<res[i].length;j++){console.log(res[i][j]);if(j!==res[i].length-1)console.log(", ");}console.log("]");if(i!==res.length-1)console.log(",\n ")}console.log("]\n");
Output
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Counting Sort (Using Constraints) - O(n ^ 2 + MAX) Time and O(MAX) Space
The idea is to use Counting Sort. Since the matrix elements are bounded in the range 1 to 10⁵, we store the frequency of each element and then rebuild the matrix in sorted order.
Let us understand with example: Input: mat[][] = [[1, 5, 3], [2, 8, 7], [4, 6, 9]]
Traverse the matrix and store the frequency of each element. For the given matrix, the frequencies of 1, 2, 3, 4, 5, 6, 7, 8, 9 become 1.
Start traversing the frequency array from 1 to 100000. Whenever freq[val] > 0, place val into the matrix and decrement its frequency.
Fill the matrix row by row: 1, 2, 3 are placed in the first row, 4, 5, 6 in the second row, and 7, 8, 9 in the third row.
After all frequencies are processed, every element has been placed in non-decreasing order.
The final sorted matrix becomes [[1, 2, 3], [4, 5, 6], [7, 8, 9]].
C++
#include<bits/stdc++.h>usingnamespacestd;vector<vector<int>>sortedMatrix(vector<vector<int>>mat){intn=mat.size();// Frequency array.vector<int>freq(100001,0);for(inti=0;i<n;i++){for(intj=0;j<n;j++){freq[mat[i][j]]++;}}// Fill matrix with sorted elements.introw=0,col=0;for(intval=1;val<=100000;val++){while(freq[val]--){mat[row][col]=val;col++;if(col==n){col=0;row++;}}}returnmat;}intmain(){vector<vector<int>>mat={{1,5,3},{2,8,7},{4,6,9}};vector<vector<int>>res=sortedMatrix(mat);cout<<"[";for(inti=0;i<res.size();i++){cout<<"[";for(intj=0;j<res[i].size();j++){cout<<res[i][j];if(j!=res[i].size()-1)cout<<", ";}cout<<"]";if(i!=res.size()-1)cout<<",\n ";}cout<<"]\n";return0;}
Java
importjava.util.ArrayList;importjava.util.Arrays;publicclassGFG{publicstaticint[][]sortedMatrix(int[][]mat){intn=mat.length;// Frequency array.int[]freq=newint[100001];for(inti=0;i<n;i++){for(intj=0;j<n;j++){freq[mat[i][j]]++;}}// Fill matrix with sorted elements.introw=0,col=0;for(intval=1;val<=100000;val++){while(freq[val]-->0){mat[row][col]=val;col++;if(col==n){col=0;row++;}}}returnmat;}publicstaticvoidmain(String[]args){int[][]mat={{1,5,3},{2,8,7},{4,6,9}};int[][]res=sortedMatrix(mat);System.out.print("[");for(inti=0;i<res.length;i++){System.out.print("[");for(intj=0;j<res[i].length;j++){System.out.print(res[i][j]);if(j!=res[i].length-1)System.out.print(", ");}System.out.print("]");if(i!=res.length-1)System.out.print(",\n ");}System.out.print("]\n");}}
Python
defsortedMatrix(mat):n=len(mat)# Frequency array.freq=[0]*100001foriinrange(n):forjinrange(n):freq[mat[i][j]]+=1# Fill matrix with sorted elements.row=0col=0forvalinrange(1,100001):whilefreq[val]>0:mat[row][col]=valcol+=1ifcol==n:col=0row+=1freq[val]-=1returnmatif__name__=="__main__":mat=[[1,5,3],[2,8,7],[4,6,9]]res=sortedMatrix(mat)print("[")foriinrange(len(res)):print("[",end="")forjinrange(len(res[i])):print(res[i][j],end="")ifj!=len(res[i])-1:print(", ",end="")print("]")ifi!=len(res)-1:print(",\n ",end="")print("]\n")
C#
usingSystem;usingSystem.Collections.Generic;classGFG{publicstaticint[][]sortedMatrix(int[][]mat){intn=mat.Length;// Frequency array.int[]freq=newint[100001];for(inti=0;i<n;i++){for(intj=0;j<n;j++){freq[mat[i][j]]++;}}// Fill matrix with sorted elements.introw=0,col=0;for(intval=1;val<=100000;val++){while(freq[val]-->0){mat[row][col]=val;col++;if(col==n){col=0;row++;}}}returnmat;}staticvoidMain(string[]args){int[][]mat=newint[][]{newint[]{1,5,3},newint[]{2,8,7},newint[]{4,6,9}};int[][]res=sortedMatrix(mat);Console.Write("[");for(inti=0;i<res.Length;i++){Console.Write("[");for(intj=0;j<res[i].Length;j++){Console.Write(res[i][j]);if(j!=res[i].Length-1)Console.Write(", ");}Console.Write("]");if(i!=res.Length-1)Console.Write(",\n ");}Console.Write("]\n");}}
JavaScript
functionsortedMatrix(mat){letn=mat.length;// Frequency array.letfreq=newArray(100001).fill(0);for(leti=0;i<n;i++){for(letj=0;j<n;j++){freq[mat[i][j]]++;}}// Fill matrix with sorted elements.letrow=0,col=0;for(letval=1;val<=100000;val++){while(freq[val]-->0){mat[row][col]=val;col++;if(col==n){col=0;row++;}}}returnmat;}// Driver codeletmat=[[1,5,3],[2,8,7],[4,6,9]];letres=sortedMatrix(mat);console.log('[');for(leti=0;i<res.length;i++){console.log('[');for(letj=0;j<res[i].length;j++){console.log(res[i][j]);if(j!=res[i].length-1)console.log(', ');}console.log(']');if(i!=res.length-1)console.log(',\n');}console.log(']');