Function BinarySearch(Lower As Integer, Upper As Integer, _
Target As String) As Integer '// Vars "Lower" and "Upper" refer to the Lower and Upper '// indices of the array being searched. "Target" is, of course, '// our target. When initially calling this function you should always '// specify Lower = Lbound(DataArray) and Upper = Ubound(DataArray)to include '// the entire array. The function returns the index of thet Target. '// This function only works correctly if you have a SORTED array of data. This can '// be easily accomplished with a sorted list box control. Considering the maximum of '// 32,768 items a listbox control can handle, this funct will need to only make 16 passes to '// Find the Target item. This Function does not match partial strings. Dim Middle As Integer '// Index of middle element '// First we check the middle element in the 'array to see if it is = to or <> our target Middle = Fix(Lower + Upper) / 2 '// Fix returns everything '// before the Decimal i.e. 9.98 = 9...this 'line only returns the middle element index If DataArray(Middle) = Target Then '// We found our String in the middle of the list BinarySearch = Middle '// Return the index of the hit Exit Function '// Job done. Gone home. End If If Lower >= Upper Then '// The list has been reduced (or is only)a Single element. Search failed. BinarySearch = -1 '// Return "-1" If Target has Not been found Exit Function '// Job done. Gone home. End If If Target < DataArray(Middle) Then '// Depending on if '//the binary value of the middle element is 'greater or less than the binary value of the 'Target we can either discard the upper or lower 'half of the [remaining]list. Upper = Middle + 1 '// Discard Upper half of list Else Lower = Middle + 1 '// Discard Lower half of list End If '// if we get to this point, we have not found 'the Target and we still have itemsin the list, 'so we call the function again (recursively) 'with revised parms... BinarySearch = BinarySearch(Lower, Upper, Target) End Function |