by Chris_Lucas (5 Submissions)
Category: String Manipulation
Compatability: Visual Basic 3.0
Difficulty: Intermediate
Date Added: Wed 3rd February 2021
Rating: (4 Votes)
This ain't your daddy's binary search tool! Mine goes about 30% faster than his. Why people insist on using the same tired and slow function I'll never know, but it suffers from two glaring weaknesses. First and foremost: < and > are about the slowest way to compare strings! Second: The tired old function assumes that you will find a match more often than not which is slow! My function doesn't suffer from either of these two "features".
Public Function FastBinarySearch(ByRef arr() As String, ByRef search As String) As Long
Dim first As Long
Dim last As Long
Dim middle As Long
first = LBound(arr)
last = UBound(arr)
Do
middle = (first + last) \ 2
Select Case StrComp(arr(middle), search, vbBinaryCompare)
Case -1: first = middle + 1
Case 1: last = middle - 1
Case 0
FastBinarySearch = middle
Exit Function
End Select
Loop Until first > last
End Function