using
System;
public
static
class
GFG {
static
void
sortByRow(
int
[, ] m)
{
for
(
int
i = 0; i < m.GetLength(0); i++) {
for
(
int
j = 0; j < m.GetLength(1); j++) {
for
(
int
k = 0; k < m.GetLength(1) - j - 1;
k++) {
if
(m[i, k] > m[i, k + 1]) {
int
t = m[i, k];
m[i, k] = m[i, k + 1];
m[i, k + 1] = t;
}
}
}
}
}
static
void
reverseArray(
int
[, ] arr)
{
for
(
int
i = 0; i < arr.GetLength(1); i++) {
int
start = 0;
int
end = arr.GetLength(0) - 1;
while
(start < end) {
int
temp = arr[i, start];
arr[i, start] = arr[i, end];
arr[i, end] = temp;
start++;
end--;
}
}
}
public
static
void
transpose(
int
[, ] mat,
int
n)
{
for
(
int
i = 0; i < n; i++) {
for
(
int
j = i + 1; j < n; j++) {
int
temp = mat[i, j];
mat[i, j] = mat[j, i];
mat[j, i] = temp;
}
}
}
public
static
void
sortMatRowAndColWise(
int
[, ] mat,
int
n)
{
sortByRow(mat);
transpose(mat, n);
sortByRow(mat);
reverseArray(mat);
transpose(mat, n);
}
public
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(
" "
);
}
Console.Write(
"\n"
);
}
}
internal
static
void
Main()
{
int
n = 3;
int
[, ] mat
= { { 3, 2, 1 }, { 9, 8, 7 }, { 6, 5, 4 } };
Console.Write(
"Original Matrix:\n"
);
printMat(mat, n);
sortMatRowAndColWise(mat, n);
Console.Write(
"\nMatrix After Sorting:\n"
);
printMat(mat, n);
}
}