CorArray: BinarySearch |
Searches the entire one-dimensional sorted array for a specific element, using an optionally specified IComparer interface.
Public Function BinarySearch( ByRef Arr As Variant, ByRef Value As Variant, Optional ByVal Comparer As IComparer ) As Long
The Arr must be sorted before calling this method.
If the returned value is less than the lower bound of the array, the value is a bitwise Not indication of where the value would have been found in the array. The following shows how to convert the result for a value that is not found.
Lower Bound of Arr | Conversion Method |
---|---|
Zero | Index = Not Result |
Non-zero | Index = (Not (Result - LBound(Arr))) + LBound(Arr) |
Exception | Condition |
---|---|
ArgumentNullException | Arr is uninitialized |
RankException | Arr is multidimensional. |
ArgumentException | Value is of a type that is not compatible with the elements in Arr. |
InvalidOperationException | Value is not comparable to the elements in Arr. |
The example code 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 = NewIntegers(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 End 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 Index As Long Index = CorArray.BinarySearch(Ints, Value) ' If the index is not less then then lower-bound ' of the array, then the value was found. If Index >= LBound(Ints) Then Debug.Print CorString.Format("Value [{0}] found at index [{1}].", Value, Index) Else ' The value was not found. To determine where ' the value should have been found, use Not to ' negate the returned index value. Index = Not Index Debug.Print CorString.Format("Value [{0}] should be at index [{1}].", Value, Index) End If End Sub ' This code produces the following output. ' Value [6] found at index [5]. ' Value [7] should be at index [6].