![]() |
VOOZH | about |
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-Diagram601Input : mat[][] = { {5, 4, 7},
{1, 3, 8},
{2, 9, 6} }
Output : 1 2 3
4 5 6
7 8 9Input: 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
Below is the implementation of the above approach:
1 2 3 4 5 6 7 8 9
Illustration with Example:
| I | J | Comparison Elements | Matrix | Comments |
|---|---|---|---|---|
| 0 | 0 | (0, 0) & (0, 1) | 56 7 1 4 8 | No Swap |
| 0 | 1 | (0, 1) & (0, 2) | 5 67 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 47 8 | Swapped |
| 0 | 4 | (1, 1) & (1, 2) | 5 6 1 4 78 | No Swap |
| 1 | 0 | (0, 0) & (0, 1) | 56 1 4 7 8 | No Swap |
| 1 | 1 | (0, 1) & (0, 2) | 5 16 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 67 8 | No Swap |
| 1 | 4 | (1, 1) & (1, 2) | 5 1 4 4 78 | No Swap |
| 2 | 0 | (0, 0) & (0, 1) | 15 4 6 7 8 | Swapped |
| 2 | 1 | (0, 1) & (0, 2) | 1 45 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 67 8 | No Swap |
| 2 | 4 | (1, 1) & (1, 2) | 5 1 4 4 78 | No Swap |
Performance Analysis: