Sort the given matrix

Last Updated : 10 Sep, 2026

Given an n * n matrix mat[][], sort all the elements of the matrix in non-decreasing order and return the resulting matrix.

Examples: 

Input: mat[][] = [[10, 20, 30, 40],
                 [15, 25, 35, 45],
                 [27, 29, 37, 48],
                [32, 33, 39, 50]]
Output: [[10, 15, 20, 25], 
 [27, 29, 30, 32],
  [33, 35, 37, 39],
  [40, 45, 48, 50]]
Explanation: Sorting the matrix gives this result:

max_path_sum_2_special_nodes_4

Input: mat[][] = [[1, 5, 3],
               [2, 8, 7],
               [4, 6, 9]]
Output: [[1, 2, 3], 
       [4, 5, 6],
       [7, 8, 9]]
Explanation: Sorting the matrix gives this result:

max_path_sum_2_special_nodes_5
Try It Yourself
redirect icon

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>
using namespace std;

// Function to sort the matrix in non-decreasing order.
vector<vector<int>> sortedMatrix(vector<vector<int>> mat)
{
    int n = mat.size();

    vector<int> v;

    // Flattening the matrix into a 1-dimensional vector.
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            v.push_back(mat[i][j]);

    // Sorting the vector in non-decreasing order.
    sort(v.begin(), v.end());

    int c = 0;

    // Reshaping the 1-dimensional vector back into the matrix.
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            mat[i][j] = v[c++];

    // Returning the sorted matrix.
    return mat;
}

int main()
{
    vector<vector<int>> mat = {{1, 5, 3}, {2, 8, 7}, {4, 6, 9}};

    vector<vector<int>> res = sortedMatrix(mat);

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        cout << "[";

        for (int j = 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";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

// Function to sort the matrix in non-decreasing order.
public class GFG {
    public static int[][] sortedMatrix(int[][] mat)
    {
        int n = mat.length;

        ArrayList<Integer> v = new ArrayList<>();

        // Flattening the matrix into a 1-dimensional
        // vector.
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                v.add(mat[i][j]);

        // Sorting the vector in non-decreasing order.
        Collections.sort(v);

        int c = 0;

        // Reshaping the 1-dimensional vector back into the
        // matrix.
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                mat[i][j] = v.get(c++);

        // Returning the sorted matrix.
        return mat;
    }

    public static void main(String[] args)
    {
        int[][] mat
            = { { 1, 5, 3 }, { 2, 8, 7 }, { 4, 6, 9 } };

        int[][] res = sortedMatrix(mat);

        System.out.print("[");
        for (int i = 0; i < res.length; i++) {
            System.out.print("[");
            for (int j = 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
def sortedMatrix(mat):
    n = len(mat)

    v = []

    # Flattening the matrix into a 1-dimensional vector.
    for i in range(n):
        for j in range(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.
    for i in range(n):
        for j in range(n):
            mat[i][j] = v[c]
            c += 1

    # Returning the sorted matrix.
    return mat


if __name__ == "__main__":
    mat = [[1, 5, 3], [2, 8, 7], [4, 6, 9]]

    res = sortedMatrix(mat)

    print("[")
    for i in range(len(res)):
        print("[", end="")
        for j in range(len(res[i])):
            print(res[i][j], end="")
            if j!= len(res[i]) - 1:
                print(", ", end="")
        print("]")
        if i!= len(res) - 1:
            print(",\n ", end="")
    print("]\n")
C#
using System;
using System.Collections.Generic;
using System.Linq;

// Function to sort the matrix in non-decreasing order.
public class GFG {
    public static int[][] sortedMatrix(int[][] mat)
    {
        int n = mat.Length;

        List<int> v = new List<int>();

        // Flattening the matrix into a 1-dimensional
        // vector.
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                v.Add(mat[i][j]);

        // Sorting the vector in non-decreasing order.
        v.Sort();

        int c = 0;

        // Reshaping the 1-dimensional vector back into the
        // matrix.
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                mat[i][j] = v[c++];

        // Returning the sorted matrix.
        return mat;
    }

    public static void Main()
    {
        int[][] mat = new int[][] { new int[] { 1, 5, 3 },
                                    new int[] { 2, 8, 7 },
                                    new int[] { 4, 6, 9 } };

        int[][] res = sortedMatrix(mat);

        Console.Write("[");
        for (int i = 0; i < res.Length; i++) {
            Console.Write("[");
            for (int j = 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.
function sortedMatrix(mat)
{
    let n = mat.length;

    let v = [];

    // Flattening the matrix into a 1-dimensional vector.
    for (let i = 0; i < n; i++)
        for (let j = 0; j < n; j++)
            v.push(mat[i][j]);

    // Sorting the vector in non-decreasing order.
    v.sort((a, b) => a - b);

    let c = 0;

    // Reshaping the 1-dimensional vector back into the
    // matrix.
    for (let i = 0; i < n; i++)
        for (let j = 0; j < n; j++)
            mat[i][j] = v[c++];

    // Returning the sorted matrix.
    return mat;
}

// Driver code
let mat = [ [ 1, 5, 3 ], [ 2, 8, 7 ], [ 4, 6, 9 ] ];

let res = sortedMatrix(mat);

console.log("[");
for (let i = 0; i < res.length; i++) {
    console.log("[");
    for (let j = 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>
using namespace std;

vector<vector<int>> sortedMatrix(vector<vector<int>> mat)
{
    int n = mat.size();

    // Frequency array.
    vector<int> freq(100001, 0);

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            freq[mat[i][j]]++;
        }
    }

    // Fill matrix with sorted elements.
    int row = 0, col = 0;

    for (int val = 1; val <= 100000; val++)
    {
        while (freq[val]--)
        {
            mat[row][col] = val;

            col++;

            if (col == n)
            {
                col = 0;
                row++;
            }
        }
    }

    return mat;
}

int main()
{
    vector<vector<int>> mat = {{1, 5, 3}, {2, 8, 7}, {4, 6, 9}};

    vector<vector<int>> res = sortedMatrix(mat);

    cout << "[";
    for (int i = 0; i < res.size(); i++)
    {
        cout << "[";

        for (int j = 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";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.Arrays;

public class GFG {
    public static int[][] sortedMatrix(int[][] mat)
    {
        int n = mat.length;

        // Frequency array.
        int[] freq = new int[100001];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                freq[mat[i][j]]++;
            }
        }

        // Fill matrix with sorted elements.
        int row = 0, col = 0;

        for (int val = 1; val <= 100000; val++) {
            while (freq[val]-- > 0) {
                mat[row][col] = val;

                col++;

                if (col == n) {
                    col = 0;
                    row++;
                }
            }
        }

        return mat;
    }

    public static void main(String[] args)
    {
        int[][] mat
            = { { 1, 5, 3 }, { 2, 8, 7 }, { 4, 6, 9 } };

        int[][] res = sortedMatrix(mat);

        System.out.print("[");
        for (int i = 0; i < res.length; i++) {
            System.out.print("[");

            for (int j = 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
def sortedMatrix(mat):
    n = len(mat)

    # Frequency array.
    freq = [0] * 100001

    for i in range(n):
        for j in range(n):
            freq[mat[i][j]] += 1

    # Fill matrix with sorted elements.
    row = 0
    col = 0

    for val in range(1, 100001):
        while freq[val] > 0:
            mat[row][col] = val

            col += 1

            if col == n:
                col = 0
                row += 1
            freq[val] -= 1

    return mat


if __name__ == "__main__":
    mat = [[1, 5, 3], [2, 8, 7], [4, 6, 9]]

    res = sortedMatrix(mat)

    print("[")
    for i in range(len(res)):
        print("[", end="")
        for j in range(len(res[i])):
            print(res[i][j], end="")
            if j != len(res[i]) - 1:
                print(", ", end="")
        print("]")
        if i != len(res) - 1:
            print(",\n ", end="")
    print("]\n")
C#
using System;
using System.Collections.Generic;

class GFG {
    public static int[][] sortedMatrix(int[][] mat)
    {
        int n = mat.Length;

        // Frequency array.
        int[] freq = new int[100001];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                freq[mat[i][j]]++;
            }
        }

        // Fill matrix with sorted elements.
        int row = 0, col = 0;

        for (int val = 1; val <= 100000; val++) {
            while (freq[val]-- > 0) {
                mat[row][col] = val;

                col++;

                if (col == n) {
                    col = 0;
                    row++;
                }
            }
        }

        return mat;
    }

    static void Main(string[] args)
    {
        int[][] mat = new int[][] { new int[] { 1, 5, 3 },
                                    new int[] { 2, 8, 7 },
                                    new int[] { 4, 6, 9 } };

        int[][] res = sortedMatrix(mat);

        Console.Write("[");
        for (int i = 0; i < res.Length; i++) {
            Console.Write("[");

            for (int j = 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 sortedMatrix(mat) {
    let n = mat.length;

    // Frequency array.
    let freq = new Array(100001).fill(0);

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < n; j++) {
            freq[mat[i][j]]++;
        }
    }

    // Fill matrix with sorted elements.
    let row = 0, col = 0;

    for (let val = 1; val <= 100000; val++) {
        while (freq[val]-- > 0) {
            mat[row][col] = val;

            col++;

            if (col == n) {
                col = 0;
                row++;
            }
        }
    }

    return mat;
}

// Driver code
let mat = [[1, 5, 3], [2, 8, 7], [4, 6, 9]];

let res = sortedMatrix(mat);

console.log('[');
for (let i = 0; i < res.length; i++) {
    console.log('[');

    for (let j = 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(']');

Output
[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]
Comment