Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to calculate the median of a matrix in VB.NET

1 Answer

0 votes
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
'

 



answered Oct 5, 2025 by avibootz
...