How to search for a number in a sorted matrix in VB.NET

1 Answer

0 votes
Imports System

Class MatrixSearch
    Public Shared Function SearchMatrix(ByVal matrix As Integer(,), ByVal target As Integer) As Boolean
        Dim rows As Integer = matrix.GetLength(0)
        Dim cols As Integer = matrix.GetLength(1)
        Dim row As Integer = 0
        Dim col As Integer = cols - 1

        While row < rows AndAlso col >= 0
            Dim value As Integer = matrix(row, col)

            If value = target Then
                Console.WriteLine($"Found: i = {row} j = {col}")
                Return True
            ElseIf value > target Then
                col -= 1
            Else
                row += 1
            End If
        End While

        Console.WriteLine("Not found")
        Return False
    End Function

    Public Shared Sub Main()
        Dim matrix As Integer(,) = {
        	{2, 3, 5, 7, 8},
        	{10, 13, 17, 18, 19},
        	{25, 26, 30, 37, 38},
        	{43, 46, 50, 51, 99}}
        
		SearchMatrix(matrix, 37)
    End Sub
End Class

 
' run:
'
' Found: i = 2 j = 3
'

 



answered 1 day ago by avibootz
...