// C# implementation to sort the
// matrix row-wise and column-wise
using System;
class GFG
{
// function to sort each
// row of the matrix
static void sortByRow(int [,]mat,
int n)
{
// sorting row number 'i'
for (int i = 0; i < n ; i++)
{
for(int j = 0;
j < n - 1; j++)
{
if(mat[i, j] > mat[i, j + 1])
{
var temp = mat[i, j];
mat[i, j] = mat[i, j + 1];
mat[i, j + 1] = temp;
}
}
}
}
// function to find transpose
// of the matrix
static void transpose(int [,]mat,
int n)
{
for (int i = 0; i < n; i++)
for (int j = i + 1;
j < n; j++)
{
// swapping element at
// index (i, j) by
// element at index (j, i)
var temp = mat[i, j];
mat[i, j] = mat[j, i];
mat[j, i] = temp;
}
}
// function to sort
// the matrix row-wise
// and column-wise
static void sortMatRowAndColWise(int [,]mat,
int n)
{
// sort rows of mat[,]
sortByRow(mat, n);
// get transpose of mat[,]
transpose(mat, n);
// again sort rows of mat[,]
sortByRow(mat, n);
// again get transpose of mat[,]
transpose(mat, n);
}
// function to print the matrix
static void printMat(int [,]mat, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
Console.Write(mat[i, j] + " ");
Console.Write("\n");
}
}
// Driver code
public static void Main ()
{
int [,]mat = {{4, 1, 3},
{9, 6, 8},
{5, 2, 7}};
int n = 3;
Console.Write("Original Matrix:\n");
printMat(mat, n);
sortMatRowAndColWise(mat, n);
Console.Write("\nMatrix After Sorting:\n");
printMat(mat, n);
}
}
// This code is contributed
// by ChitraNayal