VB.net Program to Search an Item in Array Using Binary Search

You are currently viewing VB.net Program to Search an Item in Array Using Binary Search

VB.Net program to search an item in array using binary search

'VB.Net program to search an item in array using binary search.

Module Module1

    Sub Main()
        Dim arr As Integer() = New Integer(5) {}
        Dim item As Integer = 0
        Dim flag As Integer = 0

        Dim first As Integer = 0
        Dim last As Integer = 0
        Dim middle As Integer = 0
        Dim i As Integer = 0

        Console.WriteLine("Enter array elements: ")
        For i = 0 To 4 Step 1
            Console.Write("Element[{0}]: ", i)
            arr(i) = Integer.Parse(Console.ReadLine())
        Next

        Console.WriteLine("Enter item for searching: ")
        item = Integer.Parse(Console.ReadLine())

        first = 0
        last = 4
        middle = (first + last) / 2

        While first <= last
            If (arr(middle) < item) Then
                first = middle + 1
            ElseIf (arr(middle) = item) Then
                flag = middle
                GoTo out
            Else
                last = middle - 1
            End If
            middle = (first + last) / 2
        End While
out:
        If flag <> 0 Then
            Console.WriteLine("Item found at index {0} in array", flag)
        Else
            Console.WriteLine("Item is not found")
        End If
    End Sub
    
End Module
Enter array elements:
Element[0]: 10
Element[1]: 20
Element[2]: 30
Element[3]: 45
Element[4]: 66
Enter item for searching:
45
Item found at index 3 in array
Press any key to continue . . .

Ranjith Kumar

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply