ArrayList: BinarySearch

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

Parameters

Value
[ByRef] Variant. The value to search for.
Index
[ByRef] Optional. Variant. The starting index to begin the search.
Count
[ByRef] Optional. Variant. The number of elements to search in from the startindex.
Comparer
[ByVal] Optional. IComparer. A comparer to perform user-defined comparison logic.

Return Values

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

Remarks

Exceptions

Exception TypeCondition
ArgumentExceptionNeither value nor the elements in the list support the IComparable interface.
InvalidOperationExceptionvalue and the elements in the array are not of the same datatype.

Example

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    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.

See Also

Class ArrayList Overview ArrayList Properties ArrayList Methods AddRange Capacity (get) IComparer IComparable