Imports System
Class MedianMatrix
Const ROWSCOLS As Integer = 4
Private Shared Function FindMedianUnsortedMatrix(ByVal matrix As Integer(,)) As Double
Dim rows As Integer = matrix.GetLength(0)
Dim cols As Integer = matrix.GetLength(1)
Dim total As Integer = rows * cols
Dim elements As Integer() = New Integer(total - 1) {}
Dim k As Integer = 0
For i As Integer = 0 To rows - 1
For j As Integer = 0 To cols - 1
elements(Math.Min(System.Threading.Interlocked.Increment(k), k - 1)) = matrix(i, j)
Next
Next
Array.Sort(elements)
If total Mod 2 = 1 Then
Return elements(total / 2)
Else
Return (elements(total / 2 - 1) + elements(total / 2)) / 2.0
End If
End Function
Public Shared Sub Main()
Dim matrix As Integer(,) = New Integer(3, 3) {
{5, 8, 9, 10},
{1, 4, 6, 13},
{7, 3, 0, 18},
{6, 8, 9, 20}}
Dim median As Double = FindMedianUnsortedMatrix(matrix)
Console.WriteLine($"Median of the matrix is: {median}")
End Sub
End Class
' run:
'
' Median of the matrix is: 7.5
'