How to sort each row from a two-dimensional rectangular array in C#

1 Answer

0 votes
using System;

class Program
{
    static void Main(string[] args)
    {
        int[,] array = {
            { 5, 8, 2 },
            { 4, 1, 7 },
            { 3, 9, 6 }
        };

        SortRows(array);

        Print2DArray(array);
    }

    // Function to sort each row of a 2D array
    static void SortRows(int[,] array) {
        int rows = array.GetLength(0);
        int cols = array.GetLength(1);
        
        for (int i = 0; i < rows; i++) {
            int[] row = new int[cols];
            for (int j = 0; j < cols; j++)  {
                row[j] = array[i, j];
            }
            
            Array.Sort(row);
            
            for (int j = 0; j < rows; j++) {
                array[i, j] = row[j];
            }
        }
    }

    static void Print2DArray(int[,] array) {
        int rows = array.GetLength(0);
        int cols = array.GetLength(1);
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                Console.Write(array[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}



/*
run:

2 5 8 
1 4 7 
3 6 9 

*/

 



answered Mar 15, 2025 by avibootz
edited Mar 15, 2025 by avibootz
...