How to sort each column of a matrix with strings in VB.NET

1 Answer

0 votes
Imports System

Class MatrixColumnSorter
    Private Shared Sub SortColumns(ByVal matrix As String(,))
        Dim rows As Integer = matrix.GetLength(0)
        Dim cols As Integer = matrix.GetLength(1)

        For col As Integer = 0 To cols - 1
            Dim column As String() = New String(rows - 1) {}

            For row As Integer = 0 To rows - 1
                column(row) = matrix(row, col)
            Next

            Array.Sort(column)

            For row As Integer = 0 To rows - 1
                matrix(row, col) = column(row)
            Next
        Next
    End Sub

    Private Shared Sub PrintMatrix(ByVal matrix As String(,))
        Dim rows As Integer = matrix.GetLength(0)
        Dim cols As Integer = matrix.GetLength(1)

        For row As Integer = 0 To rows - 1
            For col As Integer = 0 To cols - 1
                Console.Write(matrix(row, col) & " ")
            Next

            Console.WriteLine()
        Next
    End Sub

    Public Shared Sub Main()
        Dim matrix As String(,) = {
        	{"ccc", "zzzz", "x"},
        	{"eeee", "aaa", "ffff"},
        	{"uu", "hhh", "uuu"},
        	{"bbb", "gg", "yyyyyy"}}

        Console.WriteLine("Original Matrix:")
        PrintMatrix(matrix)

        SortColumns(matrix)

		Console.WriteLine(Environment.NewLine & "Sorted Matrix:")
        PrintMatrix(matrix)
    End Sub
End Class


 
' run
'
' Original Matrix:
' ccc zzzz x 
' eeee aaa ffff 
' uu hhh uuu 
' bbb gg yyyyyy 
' 
' Sorted Matrix:
' bbb aaa ffff 
' ccc gg uuu 
' eeee hhh x 
' uu zzzz yyyyyy 
'

 



answered Jun 2, 2025 by avibootz
...