ArrayList: BinarySearch

BinarySearch

Searches the entire sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.



 Public Function BinarySearch(
	  ByRef Value As Variant,
	  Optional ByVal Comparer As IComparer ) As Long

Parameters

Value
[ByRef] Variant. The value to search for. The value can be Null or Empty.
Comparer
[ByVal] Optional. IComparer. A comparer object to use when comparing values.
-or-
Nothing to use the default comparer.

Return Values

Long -  The index at which the value was found, or a negative value indicating the value was not found.

Remarks

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.

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.

Exceptions

ExceptionCondition
ArgumentException Comparer is Nothing and neither Value nor the elements in the list support the IComparable interface.
InvalidOperationException Comparer is Nothing and Value is not the same type as the elements in the ArrayList.

Examples

The following code demonstrates how to search for a value in an ArrayList using BinarySearch.

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
    Debug.Print "The ArrayList contains:"
    PrintValues List
    
    ' Find a non-existing value
    FindValue List, 7
    
    ' Find an existing value
    FindValue List, 4
End Sub

Private Sub PrintValues(ByVal en As IEnumerable)
    Dim v As Variant
    
    Debug.Print vbTab;
    
    For Each v In en
        Debug.Print CorString.Format("{0} ", v);
    Next v
    
    Debug.Print
End Sub

Private Sub FindValue(ByVal List As ArrayList, ByVal value As Variant)
    Dim Index As Long
    
    Index = List.BinarySearch(value)
    
    If Index < 0 Then
        Debug.Print CorString.Format("The value ({0}) was not found in the list. The next largest value was found at index {1}.", value, Not Index)
    Else
        Debug.Print CorString.Format("the value ({0}) was found at index {1}.", value, Index)
    End If
End 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.

See Also

Project CorLib Overview

Class ArrayList Overview

IComparer

IComparable