Binary Search Code

Below are two VB.NET implementations of a binary search function, one that uses iteration and another that uses recursion.

An array is declared at the form level and initialised by the form’s load event.

The array is passed to the iterative function as a parameter, along with the target, when the function is called.

The recursive function is passed the low and high bounds of the array along with the target.  Each time the low or high pointer is redefined, the recursive function calls itself again passing in the modified value of the pointer.

Public Class Form1
    Dim iData(21) As Integer
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        iData(0) = 1
        iData(1) = 2
        iData(2) = 4
        iData(3) = 7
        iData(4) = 8
        iData(5) = 12
        iData(6) = 14
        iData(7) = 15
        iData(8) = 17
        iData(9) = 18
        iData(10) = 19
        iData(11) = 24
        iData(12) = 27
        iData(13) = 31
        iData(14) = 41
        iData(15) = 53
        iData(16) = 58
        iData(17) = 62
        iData(18) = 63
        iData(19) = 85
        iData(20) = 93
        iData(21) = 95
    End Sub
 
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        MsgBox(BinarySearch(iData, 63))
    End Sub
 
    Function BinarySearch(DataArray As Object, Target As Integer) As Boolean
 
        Dim iLow As Integer, iHigh As Integer, iMiddle As Integer
        Dim bFound As Boolean
 
        iLow = LBound(DataArray)
        iHigh = UBound(DataArray)
 
        Do While iLow <= iHigh
            iMiddle = (iLow + iHigh) / 2
            If Target = DataArray(iMiddle) Then
                bFound = True
                Exit Do
            ElseIf Target < DataArray(iMiddle) Then
                iHigh = (iMiddle - 1)
            Else
                iLow = (iMiddle + 1)
            End If
        Loop
 
        If bFound = False Then
            Return False
        Else
            Return True
        End If
 
    End Function
 
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        MsgBox(BinarySearchRecursive(0, 21, 63))
    End Sub
 
    Function BinarySearchRecursive(iLow As Integer, iHigh As Integer, Target As Integer) As Boolean
 
        Dim bFound As Boolean
        Dim iMiddle As Integer
        iMiddle = (iLow + iHigh) / 2
 
        If Target = iData(iMiddle) Then
            bFound = True
        ElseIf iLow > iHigh Then
            bFound = False
        ElseIf Target < iData(iMiddle) Then
            bFound = BinarySearchRecursive(iLow, iMiddle - 1, Target)
        Else
            bFound = BinarySearchRecursive(iMiddle + 1, iHigh, Target)
        End If
 
        If bFound = False Then
            Return False
        Else
            Return True
        End If
    End Function
 
End Class