How to find the k closest elements to a giving value in sorted array with VB.NET

1 Answer

0 votes
Imports System

Public Class Program
	Public Shared Sub findKClosestElements(ByVal arr As Integer(), ByVal k As Integer, ByVal value As Integer)
        Dim left As Integer = 0
        Dim right As Integer = arr.Length - 1

        While right - left >= k
            If Math.Abs(arr(left) - value) > Math.Abs(arr(right) - value) Then
                left += 1
            Else
                right -= 1
            End If
        End While

        While left <= right
            Console.Write(arr(left) & " ")
            left += 1
        End While
    End Sub

    Public Shared Sub Main(ByVal args As String())
        Dim arr As Integer() = New Integer() {6, 10, 12, 15, 17, 18, 20, 25, 28}
        Dim value As Integer = 16, k As Integer = 4
		
        findKClosestElements(arr, k, value)
    End Sub
End Class



' run:
'
' 12 15 17 18
'

 



answered Jan 21, 2024 by avibootz
...