Binary Search
Also known as half-interval search, logarithmic search, or binary chop.
A binary search is a search algorithm that can find the position of a value within a sorted array.
The function does not return the position, it just returns whether a match was found or not.
Your array must be sorted in Ascending Order for this function to work.
Public Sub BinarySearch()
Dim myArray(0 To 3) As String
Dim bfoundMatch As String
myArray(0) = "four"
myArray(1) = "one"
myArray(2) = "three"
myArray(3) = "two"
bfoundMatch = Array_Find(myArray, "three")
Debug.Print bfoundMatch
End Sub
Public Function Array_Find(ByRef theArray() As String, _
ByVal target As String) _
As Boolean
Dim bfind As Boolean
Dim low As Integer
Dim high As Integer
Dim middle As Integer
low = 0
high = UBound(theArray)
bfind = False
Do While low <= high
middle = (low + high) / 2
If target = theArray(middle) Then
bfind = True
Exit Do
ElseIf target < theArray(middle) Then
high = (middle - 1)
Else
low = (middle + 1)
End If
Loop
Array_Find = bfind
End Function
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext