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,950 questions

51,892 answers

573 users

How to find the pair in array whose sum is nearest to a number N in a sorted array in VB.NET

1 Answer

0 votes
Imports System

Public Class Program
	Public Shared Sub Main()
        Dim arr As Integer() = {3, 5, 7, 12, 18, 20, 23, 27, 30}
        Dim size As Integer = arr.Length
        
		Dim N As Integer = 22
        
		Dim left As Integer = 0, right As Integer = size - 1, sum As Integer = 0
        Dim nearest As Integer = Int32.MaxValue, nearest_sum As Integer = 0
        Dim paira As Integer = 0, pairb As Integer = 0

        While left < right
            sum = arr(left) + arr(right)

            If Math.Abs(N - sum) < nearest Then
                nearest = Math.Abs(N - sum)
                nearest_sum = sum
                paira = arr(left)
                pairb = arr(right)
            End If

            If sum > N Then
                right -= 1
            ElseIf sum <= N Then
                left += 1
            End If
        End While

        Console.WriteLine(nearest_sum)
        Console.Write("{0} {1}", paira, pairb)
    End Sub
End Class




' run:
'
' 23
' 3 20 
'

 



answered Dec 9, 2021 by avibootz
...