VB .NET Program to Implement Binary Search

VB .NET Program to Implement Binary Search

Searching efficiently is one of the most important skills in programming. When you have a large amount of data, checking every element one by one becomes slow and impractical. This is where Binary Search comes in. Binary Search is a fast searching algorithm that works by repeatedly dividing a sorted list in half to find a target value. Because it eliminates half of the remaining elements in each step, it is much faster than Linear Search, especially for large datasets.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Binary Search is widely used in software development, from database queries to real-time search systems. It is especially useful whenever the data is already sorted. By understanding Binary Search, beginners can improve their problem-solving skills and learn how algorithms can optimize performance, which is essential for writing efficient and responsive applications in VB .NET.

Program 1: Binary Search Using Iterative Approach

This program demonstrates Binary Search using a for loop logic with a while loop, searching for a number in a sorted array.

Module Module1

    Sub Main()

        Dim data() As Integer = {1, 3, 5, 7, 9, 11, 13}
        Dim target As Integer = 7
        Dim low As Integer = 0
        Dim high As Integer = data.Length - 1
        Dim found As Boolean = False

        While low <= high

            Dim mid As Integer = (low + high) \ 2

            If data(mid) = target Then

                Console.WriteLine("Element found at position: " & mid)
                found = True

                Exit While

            ElseIf data(mid) < target Then
                low = mid + 1
            Else
                high = mid - 1
            End If

        End While

        If Not found Then
            Console.WriteLine("Element not found in the array.")
        End If

        Console.ReadLine()

    End Sub

End Module

The program keeps dividing the array into halves by calculating the middle index. It then compares the target with the middle element, adjusting the search range based on whether the target is smaller or larger. Beginners can appreciate how Binary Search reduces comparisons, making it faster than Linear Search.

Program 2: Binary Search Using Recursive Function

This version implements Binary Search using recursion, which is a natural way to express the “divide-and-conquer” logic of the algorithm.

Module Module1

    Function BinarySearch(arr() As Integer, target As Integer, low As Integer, high As Integer) As Integer

        If low > high Then
            Return -1
        End If

        Dim mid As Integer = (low + high) \ 2

        If arr(mid) = target Then
            Return mid
        ElseIf arr(mid) < target Then
            Return BinarySearch(arr, target, mid + 1, high)
        Else
            Return BinarySearch(arr, target, low, mid - 1)
        End If

    End Function

    Sub Main()

        Dim data() As Integer = {2, 4, 6, 8, 10, 12}
        Dim target As Integer = 10
        Dim result As Integer = BinarySearch(data, target, 0, data.Length - 1)

        If result <> -1 Then
            Console.WriteLine("Element found at position: " & result)
        Else
            Console.WriteLine("Element not found in the array.")
        End If

        Console.ReadLine()

    End Sub

End Module

The recursive approach calls the same function on either the left or right half of the array until the element is found or the search space is empty. This approach demonstrates the power of recursion and shows beginners a clean way to implement divide-and-conquer algorithms.

Program 3: Binary Search for Negative Numbers

Binary Search works perfectly with negative numbers as long as the array is sorted. This program searches an array containing negative and positive values.

Module Module1

    Sub Main()

        Dim data() As Integer = {-20, -10, -5, 0, 5, 10}
        Dim target As Integer = -5
        Dim low As Integer = 0
        Dim high As Integer = data.Length - 1
        Dim found As Boolean = False

        While low <= high

            Dim mid As Integer = (low + high) \ 2

            If data(mid) = target Then

                Console.WriteLine("Element found at position: " & mid)
                found = True

                Exit While

            ElseIf data(mid) < target Then
                low = mid + 1
            Else
                high = mid - 1
            End If

        End While

        If Not found Then
            Console.WriteLine("Element not found in the array.")
        End If

        Console.ReadLine()

    End Sub

End Module

The logic remains identical to standard Binary Search. Negative numbers do not affect comparisons, making the algorithm versatile for any sorted numeric data.

Program 4: Binary Search for Floating-Point Numbers

Binary Search can also be applied to floating-point numbers in a sorted array.

Module Module1

    Sub Main()

        Dim data() As Double = {0.5, 1.2, 2.3, 3.7, 4.5}
        Dim target As Double = 3.7
        Dim low As Integer = 0
        Dim high As Integer = data.Length - 1
        Dim found As Boolean = False

        While low <= high

            Dim mid As Integer = (low + high) \ 2

            If data(mid) = target Then

                Console.WriteLine("Element found at position: " & mid)
                found = True

                Exit While

            ElseIf data(mid) < target Then
                low = mid + 1
            Else
                high = mid - 1
            End If

        End While

        If Not found Then
            Console.WriteLine("Element not found in the array.")
        End If

        Console.ReadLine()

    End Sub

End Module

Binary Search works for decimal numbers because comparisons work for any numeric type. Beginners can learn how the same logic applies to integers, negative numbers, and floating-point numbers.

Program 5: Binary Search with User Input

This program allows users to enter a sorted list of numbers and a target value to search.

Module Module1

    Sub Main()

        Console.WriteLine("Enter sorted numbers separated by space:")

        Dim input As String = Console.ReadLine()
        Dim data() As Integer = Array.ConvertAll(input.Split(" "c), Function(s) Int32.Parse(s))

        Console.WriteLine("Enter number to search:")

        Dim target As Integer = Int32.Parse(Console.ReadLine())

        Dim low As Integer = 0
        Dim high As Integer = data.Length - 1
        Dim found As Boolean = False

        While low <= high

            Dim mid As Integer = (low + high) \ 2

            If data(mid) = target Then

                Console.WriteLine("Element found at position: " & mid)
                found = True

                Exit While

            ElseIf data(mid) < target Then
                low = mid + 1
            Else
                high = mid - 1
            End If

        End While

        If Not found Then
            Console.WriteLine("Element not found in the array.")
        End If

        Console.ReadLine()

    End Sub

End Module

This interactive program demonstrates how Binary Search can be integrated with user input. Beginners can practice real-world applications and understand how algorithms work with dynamic data.

Frequently Asked Questions (FAQ)

Here are some common questions beginners ask about Binary Search:

Q1: Can Binary Search work with negative numbers?
Yes. Binary Search works with negative numbers as long as the array is sorted.

Q2: Can Binary Search handle floating-point numbers?
Yes. The algorithm works for decimals and integers because it relies on comparisons, not data type.

Q3: Do arrays need to be sorted for Binary Search?
Absolutely. Sorting is mandatory; unsorted data will give incorrect results.

Q4: Is Binary Search faster than Linear Search?
Yes. Binary Search has a time complexity of O(log n), making it much faster for large datasets than Linear Search’s O(n).

Q5: Can Binary Search be implemented recursively?
Yes. Recursion is a natural way to implement Binary Search and helps beginners understand divide-and-conquer strategies.

Conclusion

Binary Search is a fast and efficient searching algorithm for sorted datasets. By exploring iterative, recursive, negative numbers, floating-point numbers, and user input examples, beginners can gain a solid understanding of how to implement it in VB .NET. Practicing Binary Search strengthens problem-solving skills and prepares beginners for more advanced algorithms like Interpolation Search, Jump Search, or Ternary Search. Mastering this fundamental algorithm lays the foundation for writing faster and more efficient applications.

Scroll to Top