Partager via


Array.BinarySearch<T> Method (array<T[], T, IComparer<T>)

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Searches an entire one-dimensional sorted Array for a value using the specified IComparer<T> generic interface.

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

Syntax

'Declaration
Public Shared Function BinarySearch(Of T) ( _
    array As T(), _
    value As T, _
    comparer As IComparer(Of T) _
) As Integer
public static int BinarySearch<T>(
    T[] array,
    T value,
    IComparer<T> comparer
)

Type Parameters

  • T
    The type of the elements of the array.

Parameters

  • array
    Type: array<T[]
    The sorted one-dimensional, zero-based Array to search.
  • value
    Type: T
    The object to search for.

Return Value

Type: System.Int32
The index of the specified value in the specified array, if value is found. If value is not found and value is less than one or more elements in array, a negative number which is the bitwise complement of the index of the first element that is larger than value. If value is not found and value is greater than any of the elements in array, a negative number which is the bitwise complement of (the index of the last element plus 1).

Exceptions

Exception Condition
ArgumentNullException

array is nulla null reference (Nothing in Visual Basic).

ArgumentException

comparer is nulla null reference (Nothing in Visual Basic), and value is of a type that is not compatible with the elements of array.

InvalidOperationException

comparer is nulla null reference (Nothing in Visual Basic), value does not implement the IComparable<T> generic interface, and the search encounters an element that does not implement the IComparable<T> generic interface.

Remarks

If the Array does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operator (~) to the negative result (in Visual Basic, Xor the negative result with -1) to produce an index. If this index is greater than or equal to the size of the array, there are no elements larger than value in the array. Otherwise, it is the index of the first element that is larger than value.

The comparer customizes how the elements are compared.

If comparer is not nulla null reference (Nothing in Visual Basic), the elements of array are compared to the specified value using the specified IComparer<T> generic interface implementation. The elements of array must already be sorted in increasing value according to the sort order defined by comparer; otherwise, the result might be incorrect.

If comparer is nulla null reference (Nothing in Visual Basic), the comparison is done using the IComparable<T> generic interface implementation provided by the element itself or by the specified value. The elements of array must already be sorted in increasing value according to the sort order defined by the IComparable<T> implementation; otherwise, the result might be incorrect.

NoteNote:

If comparer is nulla null reference (Nothing in Visual Basic) and value does not implement the IComparable<T> generic interface, the elements of array are not tested for IComparable<T> before the search begins. An exception is thrown if the search encounters an element that does not implement IComparable<T>.

Duplicate elements are allowed. If the Array contains more than one element equal to value, the method returns the index of only one of the occurrences, and not necessarily the first one.

nulla null reference (Nothing in Visual Basic) can always be compared with any other reference type; therefore, comparisons with nulla null reference (Nothing in Visual Basic) do not generate an exception. When sorting, nulla null reference (Nothing in Visual Basic) is considered to be less than any other object.

NoteNote:

For every element tested, value is passed to the appropriate IComparable<T> implementation, even if value is nulla null reference (Nothing in Visual Basic). That is, the IComparable<T> implementation determines how a given element compares to nulla null reference (Nothing in Visual Basic).

This method is an O(log n) operation, where n is the Length of array.

Examples

The following code example demonstrates the Sort<T>(array<T[], IComparer<T>) generic method overload and the BinarySearch<T>(array<T[], T, IComparer<T>) generic method overload.

The code example defines an alternative comparer for strings, named ReverseCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. The comparer calls the CompareTo(String) method, reversing the order of the comparands so that the strings sort high-to-low instead of low-to-high.

The array is displayed, sorted, and displayed again. Arrays must be sorted in order to use the BinarySearch method.

NoteNote:

The calls to the Sort<T>(array<T[], IComparer<T>) and BinarySearch<T>(array<T[], T, IComparer<T>) generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first argument.

The BinarySearch<T>(array<T[], T, IComparer<T>) generic method overload is then used to search for two strings, one that is not in the array and one that is. The array and the return value of the BinarySearch<T>(array<T[], T, IComparer<T>) method are passed to the ShowWhere generic method, which displays the index value if the string is found, and otherwise the elements the search string would fall between if it were in the array. The index is negative if the string is not n the array, so the ShowWhere method takes the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) to obtain the index of the first element in the list that is larger than the search string.

Imports System.Collections.Generic

Public Class ReverseComparer
   Implements IComparer(Of String)

   Public Function Compare(ByVal x As String, _
       ByVal y As String) As Integer _
       Implements IComparer(Of String).Compare

      ' Compare y and x in reverse order.
      Return y.CompareTo(x)

   End Function
End Class

Public Class Example

   Public Shared Sub Demo(ByVal outputBlock As System.Windows.Controls.TextBlock)

      Dim dinosaurs() As String = { _
          "Pachycephalosaurus", _
          "Amargasaurus", _
          "Tyrannosaurus", _
          "Mamenchisaurus", _
          "Deinonychus", _
          "Edmontosaurus"}

      outputBlock.Text &= vbCrLf
      For Each dinosaur As String In dinosaurs
         outputBlock.Text &= dinosaur & vbCrLf
      Next

      Dim rc As New ReverseComparer()

      outputBlock.Text &= vbLf & "Sort" & vbCrLf
      Array.Sort(dinosaurs, rc)

      outputBlock.Text &= vbCrLf
      For Each dinosaur As String In dinosaurs
         outputBlock.Text &= dinosaur & vbCrLf
      Next

      outputBlock.Text &= vbLf & _
          "BinarySearch for 'Coelophysis':" & vbCrLf
      Dim index As Integer = _
          Array.BinarySearch(dinosaurs, "Coelophysis", rc)
      ShowWhere(outputBlock, dinosaurs, index)

      outputBlock.Text &= vbLf & _
          "BinarySearch for 'Tyrannosaurus':" & vbCrLf
      index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
      ShowWhere(outputBlock, dinosaurs, index)

   End Sub

   Private Shared Sub ShowWhere(Of T) _
       (ByVal outputBlock As System.Windows.Controls.TextBlock, ByVal array() As T, ByVal index As Integer)

      If index < 0 Then
         ' If the index is negative, it represents the bitwise
         ' complement of the next larger element in the array.
         '
         index = index Xor -1

         outputBlock.Text &= "Not found. Sorts between: "

         If index = 0 Then
            outputBlock.Text &= "beginning of array and "
         Else
            outputBlock.Text &= String.Format("{0} and ", array(index - 1))
         End If

         If index = array.Length Then
            outputBlock.Text &= "end of array." & vbCrLf
         Else
            outputBlock.Text &= String.Format("{0}.", array(index)) & vbCrLf
         End If
      Else
         outputBlock.Text &= String.Format("Found at index {0}.", index) & vbCrLf
      End If

   End Sub

End Class

' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Tyrannosaurus
'Mamenchisaurus
'Deinonychus
'Edmontosaurus
'
'Sort
'
'Tyrannosaurus
'Pachycephalosaurus
'Mamenchisaurus
'Edmontosaurus
'Deinonychus
'Amargasaurus
'
'BinarySearch for 'Coelophysis':
'Not found. Sorts between: Deinonychus and Amargasaurus.
'
'BinarySearch for 'Tyrannosaurus':
'Found at index 0.
using System;
using System.Collections.Generic;

public class ReverseComparer : IComparer<string>
{
   public int Compare(string x, string y)
   {
      // Compare y and x in reverse order.
      return y.CompareTo(x);
   }
}

public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      string[] dinosaurs = {"Pachycephalosaurus", 
                              "Amargasaurus", 
                              "Tyrannosaurus", 
                              "Mamenchisaurus", 
                              "Deinonychus", 
                              "Edmontosaurus"};

      outputBlock.Text += "\n";
      foreach (string dinosaur in dinosaurs)
      {
         outputBlock.Text += dinosaur + "\n";
      }

      ReverseComparer rc = new ReverseComparer();

      outputBlock.Text += "\nSort" + "\n";
      Array.Sort(dinosaurs, rc);

      outputBlock.Text += "\n";
      foreach (string dinosaur in dinosaurs)
      {
         outputBlock.Text += dinosaur + "\n";
      }

      outputBlock.Text += "\nBinarySearch for 'Coelophysis':" + "\n";
      int index = Array.BinarySearch(dinosaurs, "Coelophysis", rc);
      ShowWhere(outputBlock, dinosaurs, index);

      outputBlock.Text += "\nBinarySearch for 'Tyrannosaurus':" + "\n";
      index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc);
      ShowWhere(outputBlock, dinosaurs, index);
   }

   private static void ShowWhere<T>(System.Windows.Controls.TextBlock outputBlock, T[] array, int index)
   {
      if (index < 0)
      {
         // If the index is negative, it represents the bitwise
         // complement of the next larger element in the array.
         //
         index = ~index;

         outputBlock.Text += "Not found. Sorts between: ";

         if (index == 0)
            outputBlock.Text += "beginning of array and ";
         else
            outputBlock.Text += String.Format("{0} and ", array[index - 1]);

         if (index == array.Length)
            outputBlock.Text += "end of array." + "\n";
         else
            outputBlock.Text += String.Format("{0}.", array[index]) + "\n";
      }
      else
      {
         outputBlock.Text += String.Format("Found at index {0}.", index) + "\n";
      }
   }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Deinonychus and Amargasaurus.

BinarySearch for 'Tyrannosaurus':
Found at index 0.
 */

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.