| ArrayList: BinarySearch |
Performs a binary search for the value in the internal list.
Public Function BinarySearch( ByRef Value As Variant, Optional ByRef Index As Variant, Optional ByRef Count As Variant, Optional ByVal Comparer As IComparer ) As Long
The search assumes the ArrayList is sorted.
The default comparison method requires the values to be of the same intrinsic Visual Basic datatype. A vbLong will fail to compare against a vbInteger, for instance. Objects must implement the IComparable interface or an exception will be thrown.
The comparison behaviour can be overridden by supplying a custom IComparer compatible object.
The search can be limited to a specific range within the list instead of over the entire list.
If the return value is negative, then the value was not found in the list. To determine where the value should have been found, negate (Not) the return value.
| Exception Type | Condition |
|---|---|
| ArgumentException | Neither value nor the elements in the list support the IComparable interface. |
| InvalidOperationException | value and the elements in the array are not of the same datatype. |
Private Sub Main() Dim list As New ArrayList Dim i As Integer For i = 1 To 5 list.Add i * 2 Next i ' Display the current values in the list Console.WriteLine "The ArrayList contains:" PrintValues list '' Find a non-existing value FindValue list, 7 '' Find an existing value FindValue list, 4 Console.ReadLineEnd SubPrivate Sub PrintValues(ByVal en As IEnumerable) Dim v As Variant Console.WriteValue vbTab For Each v In en Console.WriteValue "{0} ", v Next v Console.WriteLineEnd SubPrivate Sub FindValue(ByVal list As ArrayList, ByVal value As Variant) Dim Index As Long Index = list.BinarySearch(value) If Index < 0 Then Console.WriteLine "The value ({0}) was not found in the list. The next largest value was found at index {1}.", value, Not Index Else Console.WriteLine "the value ({0}) was found at index {1}.", value, Index End IfEnd Sub'' This code produces the following output.'''' The ArrayList contains:'' 2 4 6 8 10'' The value (7) was not found in the list. the next largest value was found at index 3.'' The value (4) was found at index 1.
Project VBCorLib Overview Class ArrayList Overview ArrayList Properties ArrayList Methods AddRange Capacity (get) IComparer IComparable