Results 1 to 16 of 16

Thread: VB - Binary Search in array (array MUST be sorted)

Threaded View

  1. #1

    Thread Starter
    PowerPoster
    Join Date
    Feb 2002
    Location
    Canada, Toronto
    Posts
    5,803

    VB - Binary Search in array (array MUST be sorted)

    Use the SearchArray function do to the search

    The array to search in must be sorted when you call this function, if it's not, use the code in this thread to sort first...
    http://vbforums.com/showthread.php?s=&threadid=231925

    VB Code:
    1. Public Function SearchArray(strArr() As String, StrToSearch As String, Optional ByVal Compare As VbCompareMethod = vbBinaryCompare) As Long
    2.     '
    3.     '  Made by Michael Ciurescu (CVMichael from vbforums.com)
    4.     '  Original thread: [url]http://www.vbforums.com/showthread.php?t=231934[/url]
    5.     '
    6.     Dim FComp As Long, LComp As Long
    7.    
    8.     FComp = StrComp(StrToSearch, strArr(LBound(strArr)), Compare)
    9.     LComp = StrComp(StrToSearch, strArr(UBound(strArr)), Compare)
    10.    
    11.     If FComp = -1 Then
    12.         SearchArray = LBound(strArr) - 1 ' less than first
    13.     ElseIf FComp = 0 Then
    14.         SearchArray = LBound(strArr)  ' equal to first
    15.     ElseIf LComp = 1 Then
    16.         SearchArray = UBound(strArr) + 1 ' larger than last
    17.     ElseIf LComp = 0 Then
    18.         SearchArray = UBound(strArr) ' equal to last
    19.     Else
    20.         ' in between first and last
    21.         SearchArray = ArrBinarySearch(strArr, StrToSearch, LBound(strArr), UBound(strArr), Compare)
    22.     End If
    23. End Function
    24.  
    25. Private Function ArrBinarySearch(strArr() As String, StrToSearch As String, ByVal First As Long, ByVal Last As Long, Optional ByVal Compare As VbCompareMethod) As Long
    26.     '
    27.     '  Made by Michael Ciurescu (CVMichael from vbforums.com)
    28.     '  Original thread: [url]http://www.vbforums.com/showthread.php?t=231934[/url]
    29.     '
    30.     Dim Mid As Long, StrC As Long
    31.    
    32.     If Abs(Last - First) <= 1 Then
    33.         ArrBinarySearch = First
    34.     Else
    35.         Mid = (First + Last) \ 2
    36.         StrC = StrComp(StrToSearch, strArr(Mid), Compare)
    37.        
    38.         Select Case StrC
    39.         Case -1
    40.             ArrBinarySearch = ArrBinarySearch(strArr, StrToSearch, First, Mid)
    41.         Case 0
    42.             ArrBinarySearch = Mid
    43.         Case 1
    44.             ArrBinarySearch = ArrBinarySearch(strArr, StrToSearch, Mid, Last)
    45.         End Select
    46.     End If
    47. End Function
    Last edited by CVMichael; Nov 30th, 2005 at 11:25 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width