How to find the largest three elements in an array with VB.NET

1 Answer

0 votes
Imports System

Public Class Program
	Public Shared Sub print3largest(ByVal arr As Integer())
        Dim size As Integer = arr.Length

        If size < 3 Then
            Console.WriteLine("array size < 3")
            Return
        End If

        Dim first, second, third As Integer
		
		first = Int32.MinValue 
		second = Int32.MinValue
        third = Int32.MinValue

        For i As Integer = 0 To size - 1
            If arr(i) > first Then
                third = second
                second = first
                first = arr(i)
            ElseIf arr(i) > second Then
                third = second
                second = arr(i)
            ElseIf arr(i) > third Then
                third = arr(i)
            End If
        Next

        Console.WriteLine("The three largest elements are: " & first & " " & second & " " & third)
    End Sub

    Public Shared Sub Main()
        Dim arr As Integer() = {5, 2, 9, 6, 12, 7, 8, 3, 1, 0}
	
        print3largest(arr)
    End Sub

End Class



' run:
'
' The three largest elements are: 12 9 8
'

 



answered Dec 2, 2021 by avibootz
...