Php Program to Sort the matrix row-wise and column-wise
Last Updated :
18 Jan, 2022
Given a n x n matrix. The problem is to sort the matrix row-wise and column wise.
Examples:Â
Â
Input : mat[][] = { {4, 1, 3},
{9, 6, 8},
{5, 2, 7} }
Output : 1 3 4
2 5 7
6 8 9
Input : mat[][] = { {12, 7, 1, 8},
{20, 9, 11, 2},
{15, 4, 5, 13},
{3, 18, 10, 6} }
Output : 1 5 8 12
2 6 10 15
3 7 11 18
4 9 13 20
Â
Approach: Following are the steps:
Â
- Sort each row of the matrix.
- Get transpose of the matrix.
- Again sort each row of the matrix.
- Again get transpose of the matrix.
Algorithm for getting transpose of the matrix:Â
Â
for (int i = 0; i < n; i++) {
for (int j = i + 1; i < n; i++) {
int temp = mat[i][j];
mat[i][j] = mat[j][i];
mat[j][i] = temp;
}
}
PHP
<?php
$MAX_SIZE = 10;
function sortByRow(& $mat , $n )
{
for ( $i = 0; $i < $n ; $i ++)
sort( $mat [ $i ]);
}
function transpose(& $mat , $n )
{
for ( $i = 0; $i < $n ; $i ++)
{
for ( $j = $i + 1;
$j < $n ; $j ++)
{
$t = $mat [ $i ][ $j ];
$mat [ $i ][ $j ] = $mat [ $j ][ $i ];
$mat [ $j ][ $i ] = $t ;
}
}
}
function sortMatRowAndColWise(& $mat , $n )
{
sortByRow( $mat , $n );
transpose( $mat , $n );
sortByRow( $mat , $n );
transpose( $mat , $n );
}
function printMat(& $mat , $n )
{
for ( $i = 0; $i < $n ; $i ++)
{
for ( $j = 0; $j < $n ; $j ++)
echo $mat [ $i ][ $j ] . " " ;
echo "
";
}
}
$mat = array ( array ( 4, 1, 3 ),
array ( 9, 6, 8 ),
array ( 5, 2, 7 ));
$n = 3;
echo "Original Matrix:
";
printMat( $mat , $n );
sortMatRowAndColWise( $mat , $n );
echo "
Matrix After Sorting:
";
printMat( $mat , $n );
?>
|
Output:Â
Â
Original Matrix:
4 1 3
9 6 8
5 2 7
Matrix After Sorting:
1 3 4
2 5 7
6 8 9
Time Complexity: O(n2log2n).Â
Auxiliary Space: O(1).
Please refer complete article on Sort the matrix row-wise and column-wise for more details!
Share your thoughts in the comments
Please Login to comment...