VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-the-given-matrix-memory-efficient-approach/

⇱ Sort the given Matrix In-Place - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

👁 Untitled-Diagram601

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: 


Output
1 2 3 
4 5 6 
7 8 9

Illustration with Example:

IJComparison ElementsMatrixComments
00(0, 0) & (0, 1)56
1 4 8
No Swap
01(0, 1) & (0, 2)5 67
1 4 8
No Swap
02(0, 2) & (1, 0)5 6 1
7 4 8
Swapped
03(1, 0) & (1, 1)5 6 1 
47 8
Swapped
04(1, 1) & (1, 2)5 6 1 
4 78
No Swap
10(0, 0) & (0, 1)56
4 7 8
No Swap
11(0, 1) & (0, 2)5 16
4 7 8
Swapped
12(0, 2) & (1, 0)5 1 4
6 7 8
Swapped
13(1, 0) & (1, 1)5 1 4 
67 8
No Swap
14(1, 1) & (1, 2)5 1 4 
4 78
No Swap
20(0, 0) & (0, 1)15
6 7 8
Swapped
21(0, 1) & (0, 2)1 45
6 7 8
Swapped
22(0, 2) & (1, 0)1 4 5
6 7 8
No Swap
23(1, 0) & (1, 1)5 1 4 
67 8
No Swap
24(1, 1) & (1, 2)5 1 4 
4 78
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)


Comment
Article Tags: