cArray: BinarySearch |
Performs a binary search on a given array. A subportion of the array can be searched using the startindex and length parameters. A custom user comparer can optionally be supplied to perform special comparisons between elements in the array.
Public Function BinarySearch( ByRef Arr As Variant, ByRef Value As Variant, Optional ByRef Index As Variant, Optional ByRef Count As Variant, Optional ByVal Comparer As IComparer ) As Long
If the returned value is less than the lower bound of the array, then
the value indicates where the value would have been found in the array. The
following is how to convert the return value to the array index:
Lowerbound of 0: return = Not return
Other lowerbound: return = (Not (return - lowerbound)) + lowerbound
' This example searches a sorted list for values,'' displaying the index found, or the index the value'' should have been found.Private Sub Main() Dim ints() As Integer '' Create a sorted array with the value 7 missing. ints = cArray.NewArray(ciInteger, 1, 2, 3, 4, 5, 6, 8, 9, 10) '' Search for the value 6. Search ints, 6 '' Search for the missing value 7. Search ints, 7 '' Wait for user to press enter. Console.ReadLineEnd Sub'' Performs a binary search on the array, searching for'' the requested value. If the value is found, then the'' search index will be equal or greater than the lower-bound'' of the array, otherwise, the value was not found.Private Sub Search(ByRef ints() As Integer, ByVal Value As Integer) Dim i As Long i = cArray.BinarySearch(ints, Value) '' If the index is not less then then lower-bound '' of the array, then the value was found. If i >= LBound(ints) Then Console.WriteLine "Value [{0}] found at index [{1}].", Value, i Else '' The value was not found. To determine where '' the value should have been found, use Not to '' negate the returned index value. i = Not i Console.WriteLine "Value [{0}] should be at index [{1}].", Value, i End IfEnd Sub'' This code produces the following output.''''Value [6] found at index [5].''Value [7] should be at index [6].
Project VBCorLib Overview Class cArray Overview cArray Properties cArray Methods ciArrayTypes