How to find the starting and ending position of a given value in a sorted integer array in VB.NET

1 Answer

0 votes
Imports System

Friend Class Program
    Public Shared Function findStartingEndingPosition(ByVal arr As Integer(), ByVal value As Integer) As Integer()
        Dim result As Integer() = New Integer(1) {}
        result(0) = -1
        result(1) = -1
        Dim i As Integer = 0

        For i = 0 To arr.Length - 1 - 1
            If arr(i) = value Then
                result(0) = i
                result(1) = i
                Exit For
            End If
        Next

        For j As Integer = i To arr.Length - 1 - 1
            If arr(j) = arr(j + 1) Then
                result(1) = j + 1
            Else
                Exit For
            End If
        Next

        Return result
    End Function

    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = New Integer() {1, 3, 4, 7, 7, 8, 8, 10, 11}
        Dim value As Integer = 8
        
        Dim result As Integer() = findStartingEndingPosition(arr, value)
        
        Console.WriteLine("start: " & result(0))
        Console.WriteLine("end: " & result(1))
    End Sub
End Class




' run:
'
' start: 5
' end: 6
'

 



answered Mar 30, 2024 by avibootz
...