Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
BinarySearch Method (T)

List(Of T).BinarySearch Method (T)

Searches the entire sorted List(Of T) for an element using the default comparer and returns the zero-based index of the element.

Namespace:  System.Collections.Generic
Assembly:  mscorlib (in mscorlib.dll)

'Declaration
Public Function BinarySearch ( _
	item As T _
) As Integer

Parameters

item
Type: T
The object to locate. The value can be Nothing for reference types.

Return Value

Type: System.Int32
The zero-based index of item in the sorted List(Of T), if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.

ExceptionCondition
InvalidOperationException

The default comparer Comparer(Of T).Default cannot find an implementation of the IComparable(Of T) generic interface or the IComparable interface for type T.

This method uses the default comparer Comparer(Of T).Default for type T to determine the order of list elements. The Comparer(Of T).Default property checks whether type T implements the IComparable(Of T) generic interface and uses that implementation, if available. If not, Comparer(Of T).Default checks whether type T implements the IComparable interface. If type T does not implement either interface, Comparer(Of T).Default throws an InvalidOperationException.

The List(Of T) must already be sorted according to the comparer implementation; otherwise, the result is incorrect.

Comparing Nothing with any reference type is allowed and does not generate an exception when using the IComparable(Of T) generic interface. When sorting, Nothing is considered to be less than any other object.

If the List(Of T) contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.

If the List(Of T) does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operation (~) to this negative integer to get the index of the first element that is larger than the search value. When inserting the value into the List(Of T), this index should be used as the insertion point to maintain the sort order.

This method is an O(log n) operation, where n is the number of elements in the range.

The following code example demonstrates the Sort method overload and the BinarySearch(T) method overload. A List(Of T) of strings is created and populated with four strings, in no particular order. The list is displayed, sorted, and displayed again.

The BinarySearch(T) method overload is then used to search for two strings that are not in the list, and the Insert method is used to insert them. The return value of the BinarySearch(T) method is negative in each case, because the strings are not in the list. Taking the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) of this negative number produces the index of the first element in the list that is larger than the search string, and inserting at this location preserves the sort order. The second search string is larger than any element in the list, so the insertion position is at the end of the list.


Imports System
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs As New List(Of String)

        dinosaurs.Add("Pachycephalosaurus")
        dinosaurs.Add("Amargasaurus")
        dinosaurs.Add("Mamenchisaurus")
        dinosaurs.Add("Deinonychus")

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "Sort")
        dinosaurs.Sort

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "BinarySearch and Insert ""Coelophysis"":")
        Dim index As Integer = dinosaurs.BinarySearch("Coelophysis")
        If index < 0 Then
            index = index Xor -1
            dinosaurs.Insert(index, "Coelophysis")
        End If

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "BinarySearch and Insert ""Tyrannosaurus"":")
        index = dinosaurs.BinarySearch("Tyrannosaurus")
        If index < 0 Then
            index = index Xor -1
            dinosaurs.Insert(index, "Tyrannosaurus")
        End If

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

    End Sub
End Class

' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Deinonychus
'
'Sort
'
'Amargasaurus
'Deinonychus
'Mamenchisaurus
'Pachycephalosaurus
'
'BinarySearch and Insert "Coelophysis":
'
'Amargasaurus
'Coelophysis
'Deinonychus
'Mamenchisaurus
'Pachycephalosaurus
'
'BinarySearch and Insert "Tyrannosaurus":
'
'Amargasaurus
'Coelophysis
'Deinonychus
'Mamenchisaurus
'Pachycephalosaurus
'Tyrannosaurus


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

ADD
Show:
© 2015 Microsoft