How to find the floor of N in a sorted array with VB.NET

1 Answer

0 votes
' floor of N = the largest element in the array smaller than or equal to N

Imports System

Public Class Program
    Public Shared Function find_the_floor(ByVal arr As Integer(), ByVal N As Integer) As Integer
        Dim size As Integer = arr.Length

        If N >= arr(size - 1) Then
            Return size - 1
        End If

        If N < arr(0) Then
            Return -1
        End If

        For i As Integer = 1 To size - 1
            If arr(i) > N Then
                Return i - 1
            End If
        Next

        Return -1
    End Function

    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = New Integer() {1, 2, 7, 8, 14, 19, 20, 24, 28}
        Dim N As Integer = 17
	
        Dim index As Integer = find_the_floor(arr, N)

        If index = -1 Then
            Console.Write("The floor doesn't exist in array")
        Else
            Console.Write("The floor of " & N & " is " & arr(index))
        End If
    End Sub
End Class



' run:
'
' The floor of 17 is 14
'

 



answered Jan 20, 2024 by avibootz

Related questions

...