Sort the given Matrix In-Place
Last Updated :
12 Jul, 2025
Given a matrix of m rows and n columns, the task is to sort the matrix in the strict order that is every row is sorted in increasing order and the first element of every row is greater than the first element of the previous row.

Input : mat[][] = { {5, 4, 7},
{1, 3, 8},
{2, 9, 6} }
Output : 1 2 3
4 5 6
7 8 9
Input: mat[][] = { {5, 4, 7},
{1, 3, 8} }
Output: 1 3 4
5 7 8
The idea is to treat the 2D-Array as a 1D-Array to sort the matrix without using extra space. This can also be explained with the help of the following example.
For Example:
Consider a 2*2 Matrix with 4 elements. The idea is to treat the elements of the matrix as 1D Array of 4 elements.
As In the given matrix each element can be accessed as -
1st Element - 0th Row, 0th Col
2nd Element - 0th Row, 1st Col
3rd Element - 1st Row, 0th Col
4th Element - 1st Row, 1st Col
So, for Accessing ith element of the matrix, the relation can be defined as:
Ith Element of the Matrix = Mat[ i / n ][ i % n ]
Where n is the number of columns
- Find the number of rows(say m) and columns(say n) in the matrix by finding the length of the number of rows in the 2D-Array and the elements in each row in the Array.
- Iterate over each element of the matrix from 0 to the number of elements (m * n).
- Find the appropriate position of the element in the matrix using the above formulae for each element.
- Compare each element with the next element (For the last element in the row, the next element will be the next row first element) in the matrix, and if the next element is, less then swap these elements.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void sortMatrixInPlace(vector<vector<int>>& mat) {
int m = mat.size();
if (m == 0) return;
int n = mat[0].size();
// Sort the matrix elements in place
for (int i = 0; i < m * n - 1; i++) {
for (int j = i + 1; j < m * n; j++) {
// Convert 1D index back to 2D index
// using i/n for row and i%n for col
int row1 = i / n, col1 = i % n;
int row2 = j / n, col2 = j % n;
if (mat[row1][col1] > mat[row2][col2]) {
swap(mat[row1][col1], mat[row2][col2]);
}
}
}
}
int main() {
vector<vector<int>> mat{{5, 4, 7, 1}, {1, 3, 8, 2}, {2, 9, 6, 0}};
sortMatrixInPlace(mat);
cout << "Sorted Matrix Will be:" << endl;
for (const auto& row : mat) {
for (int x : row) {
cout << x << " ";
}
cout << endl;
}
return 0;
}
Java
// Java implementation to sort
// the given matrix in strict order
class GFG
{
// Function to sort the matrix
static void sortMat(int[][] data, int row, int col)
{
// Number of elements in matrix
int size = row * col;
// Loop to sort the matrix
// using Bubble Sort
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size - 1; j++)
{
// Condition to check
// if the Adjacent elements
if (data[j / col][j % col] > data[(j + 1)
/ col][(j + 1) % col])
{
// Swap if previous value is greater
int temp = data[j / col][j % col];
data[j / col][j % col] = data[(j + 1)
/ col][(j + 1) % col];
data[(j + 1) / col][(j + 1) % col] = temp;
}
}
}
}
static void printMat(int[][] mat, int row, int col)
{
// Loop to print the matrix
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
// Driver Code
public static void main(String[] args)
{
int[][] mat = { { 5, 4, 7 },
{ 1, 3, 8 },
{ 2, 9, 6 } };
int row = mat.length;
int col = mat[0].length;
// Function call to sort
sortMat(mat, row, col);
// Function call to
// print matrix
printMat(mat, row, col);
}
}
// This code is contributed by PrinciRaj1992
Python
# Python3 implementation to sort
# the given matrix in strict order
# Function to sort the matrix
def sortMat(data, row, col):
# Number of elements in matrix
size = row * col
# Loop to sort the matrix
# using Bubble Sort
for i in range(0, size):
for j in range(0, size-1):
# Condition to check
# if the Adjacent elements
if ( data[j//col][j % col] >\
data[(j + 1)//col][(j + 1)% col] ):
# Swap if previous value is greater
temp = data[j//col][j % col]
data[j//col][j % col] =\
data[(j + 1)//col][(j + 1)% col]
data[(j + 1)//col][(j + 1)% col] =\
temp
def printMat(mat, row, col):
# Loop to print the matrix
for i in range(row):
for j in range(col):
print(mat[i][j], end =" ")
print()
# Driver Code
if __name__ == "__main__":
mat = [ [5, 4, 7],
[1, 3, 8],
[2, 9, 6] ]
row = len(mat)
col = len(mat[0])
# Function call to sort
sortMat(mat, row, col)
# Function call to
# print matrix
printMat(mat, row, col)
C#
// C# implementation to sort
// the given matrix in strict order
using System;
class GFG
{
// Function to sort the matrix
static void sortMat(int[,] data, int row, int col)
{
// Number of elements in matrix
int size = row * col;
// Loop to sort the matrix
// using Bubble Sort
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size - 1; j++)
{
// Condition to check
// if the Adjacent elements
if (data[j / col,j % col] > data[(j + 1)
/ col,(j + 1) % col])
{
// Swap if previous value is greater
int temp = data[j / col,j % col];
data[j / col,j % col] = data[(j + 1)
/ col,(j + 1) % col];
data[(j + 1) / col,(j + 1) % col] = temp;
}
}
}
}
static void printMat(int[,] mat, int row, int col)
{
// Loop to print the matrix
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Console.Write(mat[i,j] + " ");
}
Console.WriteLine();
}
}
// Driver Code
public static void Main(String[] args)
{
int[,] mat = { { 5, 4, 7 },
{ 1, 3, 8 },
{ 2, 9, 6 } };
int row = mat.GetLength(0);
int col = mat.GetLength(1);
// Function call to sort
sortMat(mat, row, col);
// Function call to
// print matrix
printMat(mat, row, col);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript implementation to sort
// the given matrix in strict order
let N = 3;
let M = 3;
// Function to sort the matrix
function sortMat(data, row, col)
{
// Number of elements in matrix
let size = row * col;
// Loop to sort the matrix
// using Bubble Sort
for (let i = 0; i < size; i++)
{
for (let j = 0; j < size - 1; j++)
{
// Condition to check
// if the Adjacent elements
if (data[(Math.floor(j / col))][j % col] >
data[(Math.floor((j + 1) / col))][(j + 1) % col])
{
// Swap if previous value is greater
let temp = data[(Math.floor(j / col))][j % col];
data[(Math.floor(j / col))][j % col] =
data[(Math.floor((j + 1) / col))][(j + 1) % col];
data[(Math.floor((j + 1) / col))][(j + 1) % col] = temp;
}
}
}
}
function printMat(mat, row, col)
{
// Loop to print the matrix
for (let i = 0; i < row; i++)
{
for (let j = 0; j < col; j++)
{
document.write(mat[i][j] + " ");
}
document.write("<br>");
}
}
// Driver Code
let mat = [ [ 5, 4, 7 ],
[ 1, 3, 8 ],
[ 2, 9, 6 ] ];
let row = N;
let col = M;
// Function call to sort
sortMat(mat, row, col);
// Function call to
// print matrix
printMat(mat, row, col);
// This code is contributed by gfgking
</script>
Illustration with Example:
I | J | Comparison Elements | Matrix | Comments |
---|
0 | 0 | (0, 0) & (0, 1) | 5 6 7 1 4 8 | No Swap |
0 | 1 | (0, 1) & (0, 2) | 5 6 7 1 4 8 | No Swap |
0 | 2 | (0, 2) & (1, 0) | 5 6 1 7 4 8 | Swapped |
0 | 3 | (1, 0) & (1, 1) | 5 6 1 4 7 8 | Swapped |
0 | 4 | (1, 1) & (1, 2) | 5 6 1 4 7 8 | No Swap |
1 | 0 | (0, 0) & (0, 1) | 5 6 1 4 7 8 | No Swap |
1 | 1 | (0, 1) & (0, 2) | 5 1 6 4 7 8 | Swapped |
1 | 2 | (0, 2) & (1, 0) | 5 1 4 6 7 8 | Swapped |
1 | 3 | (1, 0) & (1, 1) | 5 1 4 6 7 8 | No Swap |
1 | 4 | (1, 1) & (1, 2) | 5 1 4 4 7 8 | No Swap |
2 | 0 | (0, 0) & (0, 1) | 1 5 4 6 7 8 | Swapped |
2 | 1 | (0, 1) & (0, 2) | 1 4 5 6 7 8 | Swapped |
2 | 2 | (0, 2) & (1, 0) | 1 4 5 6 7 8 | No Swap |
2 | 3 | (1, 0) & (1, 1) | 5 1 4 6 7 8 | No Swap |
2 | 4 | (1, 1) & (1, 2) | 5 1 4 4 7 8 | No Swap |
Performance Analysis:
- Time Complexity: In the given approach, we are sorting the elements in the matrix by considering the elements in the 1D-Array using Bubble sort, so the overall complexity will be O((m * n) x (m x n))
- Space Complexity: In the given approach, no extra space is used, so the overall space complexity will be O(1)
Explore
DSA Fundamentals
Data Structures
Algorithms
Advanced
Interview Preparation
Practice Problem