// C# implementation to sort the rows
// of matrix in ascending order followed by
// sorting the columns in descending order
using System;
public static class GFG {
// function to sort each row of the matrix
// according to the order specified by
// ascending.
static void sortByRow(int[, ] m)
{
// loop for rows of matrix
for (int i = 0; i < m.GetLength(0); i++) {
// loop for column of matrix
for (int j = 0; j < m.GetLength(1); j++) {
// loop for comparison and swapping
for (int k = 0; k < m.GetLength(1) - j - 1;
k++) {
if (m[i, k] > m[i, k + 1]) {
// swapping of elements
int t = m[i, k];
m[i, k] = m[i, k + 1];
m[i, k + 1] = t;
}
}
}
}
}
static void reverseArray(int[, ] arr)
{
// Traverse each row of [,]arr
for (int i = 0; i < arr.GetLength(1); i++) {
// Initialise start and end index
int start = 0;
int end = arr.GetLength(0) - 1;
// Till start < end, swap the element
// at start and end index
while (start < end) {
// Swap the element
int temp = arr[i, start];
arr[i, start] = arr[i, end];
arr[i, end] = temp;
// Increment start and decrement
// end for next pair of swapping
start++;
end--;
}
}
}
// function to find transpose of the matrix
public 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)
int temp = mat[i, j];
mat[i, j] = mat[j, i];
mat[j, i] = temp;
}
}
}
// function to sort the matrix row-wise
// and column-wise
public static void sortMatRowAndColWise(int[, ] mat,
int n)
{
// sort rows of mat[][]
sortByRow(mat);
// get transpose of mat[][]
transpose(mat, n);
// again sort rows of mat[][] in descending
// order.
sortByRow(mat);
reverseArray(mat);
// again get transpose of mat[][]
transpose(mat, n);
}
// function to print the matrix
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");
}
}
// Driver program to test above
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);
}
}
// This code is contributed by Aarti_Rathi