Array.BinarySearch Array.BinarySearch Array.BinarySearch Array.BinarySearch Method

定义

使用二进制搜索算法在一维的排序 Array 中搜索值。Searches a one-dimensional sorted Array for a value, using a binary search algorithm.

重载

BinarySearch(Array, Object) BinarySearch(Array, Object) BinarySearch(Array, Object)

使用由数组中每个元素和指定对象实现的 IComparable 接口,在整个一维排序数组中搜索特定元素。Searches an entire one-dimensional sorted array for a specific element, using the IComparable interface implemented by each element of the array and by the specified object.

BinarySearch(Array, Object, IComparer) BinarySearch(Array, Object, IComparer) BinarySearch(Array, Object, IComparer)

使用指定 IComparer 接口,在整个一维排序数组中搜索值。Searches an entire one-dimensional sorted array for a value using the specified IComparer interface.

BinarySearch(Array, Int32, Int32, Object) BinarySearch(Array, Int32, Int32, Object) BinarySearch(Array, Int32, Int32, Object)

使用由一维排序数组中每个元素和指定的值实现的 IComparable 接口,在该数组的一个元素范围内搜索值。Searches a range of elements in a one-dimensional sorted array for a value, using the IComparable interface implemented by each element of the array and by the specified value.

BinarySearch(Array, Int32, Int32, Object, IComparer) BinarySearch(Array, Int32, Int32, Object, IComparer) BinarySearch(Array, Int32, Int32, Object, IComparer)

使用指定 IComparer 接口,在一维排序数组的某个元素范围中搜索值。Searches a range of elements in a one-dimensional sorted array for a value, using the specified IComparer interface.

BinarySearch<T>(T[], T) BinarySearch<T>(T[], T) BinarySearch<T>(T[], T) BinarySearch<T>(T[], T)

使用由 Array 中每个元素和指定对象实现的 IComparable<T> 泛型接口,在整个一维排序数组中搜索特定元素。Searches an entire one-dimensional sorted array for a specific element, using the IComparable<T> generic interface implemented by each element of the Array and by the specified object.

BinarySearch<T>(T[], T, IComparer<T>) BinarySearch<T>(T[], T, IComparer<T>) BinarySearch<T>(T[], T, IComparer<T>) BinarySearch<T>(T[], T, IComparer<T>)

使用指定 IComparer<T> 泛型接口,在整个一维排序数组中搜索值。Searches an entire one-dimensional sorted array for a value using the specified IComparer<T> generic interface.

BinarySearch<T>(T[], Int32, Int32, T) BinarySearch<T>(T[], Int32, Int32, T) BinarySearch<T>(T[], Int32, Int32, T) BinarySearch<T>(T[], Int32, Int32, T)

使用由 Array 中每个元素和指定值实现的 IComparable<T> 泛型接口,在一维排序数组的某个元素范围中搜索值。Searches a range of elements in a one-dimensional sorted array for a value, using the IComparable<T> generic interface implemented by each element of the Array and by the specified value.

BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)

使用指定 IComparer<T> 泛型接口,在一维排序数组的某个元素范围中搜索值。Searches a range of elements in a one-dimensional sorted array for a value, using the specified IComparer<T> generic interface.

BinarySearch(Array, Object) BinarySearch(Array, Object) BinarySearch(Array, Object)

使用由数组中每个元素和指定对象实现的 IComparable 接口,在整个一维排序数组中搜索特定元素。Searches an entire one-dimensional sorted array for a specific element, using the IComparable interface implemented by each element of the array and by the specified object.

public:
 static int BinarySearch(Array ^ array, System::Object ^ value);
public static int BinarySearch (Array array, object value);
static member BinarySearch : Array * obj -> int

参数

array
Array Array Array Array

要搜索的排序一维 ArrayThe sorted one-dimensional Array to search.

value
Object Object Object Object

要搜索的对象。The object to search for.

返回

如果找到 value,则为指定 array 中的指定 value 的索引;否则为负数。The index of the specified value in the specified array, if value is found; otherwise, a negative number. 如果找不到 valuevalue 小于 array 中的一个或多个元素,则返回的负数是大于 value 的第一个元素的索引的按位求补。If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. 如果找不到 valuevalue 大于 array 中的所有元素,则返回的负数是(最后一个元素的索引加 1)的按位求补。If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1). 如果使用非排序的 array 调用此方法,返回值则可能不正确并且可能会返回负数,即使 value 存在于 array 中也是如此。If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if value is present in array.

异常

array 是多维的。array is multidimensional.

value 的类型与 array的元素不兼容。value is of a type that is not compatible with the elements of array.

value 不实现 IComparable 接口,并且搜索遇到不实现 IComparable 接口的元素。value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface.

示例

下面的代码示例演示如何使用BinarySearch Array在中查找特定的对象。The following code example shows how to use BinarySearch to locate a specific object in an Array.

备注

创建数组时, 其元素采用升序排序顺序。The array is created with its elements in ascending sort order. BinarySearch方法要求数组按升序排序。The BinarySearch method requires the array to be sorted in ascending order.

using namespace System;

public ref class SamplesArray
{
public:
    static void Main()
    {
        // Creates and initializes a new Array.
        Array^ myIntArray = Array::CreateInstance(Int32::typeid, 5);

        myIntArray->SetValue(8, 0);
        myIntArray->SetValue(2, 1);
        myIntArray->SetValue(6, 2);
        myIntArray->SetValue(3, 3);
        myIntArray->SetValue(7, 4);

        // Do the required sort first
        Array::Sort(myIntArray);

        // Displays the values of the Array.
        Console::WriteLine("The Int32 array contains the following:");
        PrintValues(myIntArray);

        // Locates a specific object that does not exist in the Array.
        Object^ myObjectOdd = 1;
        FindMyObject(myIntArray, myObjectOdd);

        // Locates an object that exists in the Array.
        Object^ myObjectEven = 6;
        FindMyObject(myIntArray, myObjectEven);
    }

    static void FindMyObject(Array^ myArr, Object^ myObject)
    {
        int myIndex = Array::BinarySearch(myArr, myObject);
        if (myIndex < 0)
        {
            Console::WriteLine("The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, ~myIndex);
        }
        else
        {
            Console::WriteLine("The object to search for ({0}) is at index {1}.", myObject, myIndex);
        }
    }

    static void PrintValues(Array^ myArr)
    {
        int i = 0;
        int cols = myArr->GetLength(myArr->Rank - 1);
        for each (Object^ o in myArr)
        {
            if ( i < cols )
            {
                i++;
            }
            else
            {
                Console::WriteLine();
                i = 1;
            }
            Console::Write("\t{0}", o);
        }
        Console::WriteLine();
    }
};

int main()
{
    SamplesArray::Main();
}
// This code produces the following output.
//
//The Int32 array contains the following:
//        2       3       6       7       8
//The object to search for (1) is not found. The next larger object is at index 0
//
//The object to search for (6) is at index 2.
using System;

public class SamplesArray
{
    public static void Main()
    {
        // Creates and initializes a new Array.
        Array myIntArray = Array.CreateInstance(typeof(Int32), 5);

        myIntArray.SetValue(8, 0);
        myIntArray.SetValue(2, 1);
        myIntArray.SetValue(6, 2);
        myIntArray.SetValue(3, 3);
        myIntArray.SetValue(7, 4);

        // Do the required sort first
        Array.Sort(myIntArray);

        // Displays the values of the Array.
        Console.WriteLine( "The Int32 array contains the following:" );
        PrintValues(myIntArray);

        // Locates a specific object that does not exist in the Array.
        object myObjectOdd = 1;
        FindMyObject( myIntArray, myObjectOdd );

        // Locates an object that exists in the Array.
        object myObjectEven = 6;
        FindMyObject(myIntArray, myObjectEven);
    }

    public static void FindMyObject(Array myArr, object myObject)
    {
        int myIndex=Array.BinarySearch(myArr, myObject);
        if (myIndex < 0)
        {
            Console.WriteLine("The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, ~myIndex );
        }
        else
        {
            Console.WriteLine("The object to search for ({0}) is at index {1}.", myObject, myIndex );
        }
    }

 
    public static void PrintValues(Array myArr)
    {
        int i = 0;
        int cols = myArr.GetLength(myArr.Rank - 1);
        foreach (object o in myArr)
        {
            if ( i < cols )
            {
                i++;
            }
            else
            {
                Console.WriteLine();
                i = 1;
            }
            Console.Write( "\t{0}", o);
        }
        Console.WriteLine();
    }
}
// This code produces the following output.
//
//The Int32 array contains the following:
//        2       3       6       7       8
//The object to search for (1) is not found. The next larger object is at index 0
//
//The object to search for (6) is at index 2.
Imports System

Public Class SamplesArray
    Public Shared Sub Main()
        ' Creates and initializes a new Array.
        Dim myIntArray As Array = Array.CreateInstance( GetType(Int32), 5 )

        myIntArray.SetValue( 8, 0 )
        myIntArray.SetValue( 2, 1 )
        myIntArray.SetValue( 6, 2 )
        myIntArray.SetValue( 3, 3 )
        myIntArray.SetValue( 7, 4 )

        ' Do the required sort first
        Array.Sort(myIntArray)

        ' Displays the values of the Array.
        Console.WriteLine("The Int32 array contains the following:")
        PrintValues(myIntArray)

        ' Locates a specific object that does not exist in the Array.
        Dim myObjectOdd As Object = 1
        FindMyObject(myIntArray, myObjectOdd)

        ' Locates an object that exists in the Array.
        Dim myObjectEven As Object = 6
        FindMyObject(myIntArray, myObjectEven)
    End Sub

    Public Shared Sub FindMyObject(myArr As Array, myObject As Object)
        Dim myIndex As Integer = Array.BinarySearch(myArr, myObject)
        If  myIndex < 0 Then
            Console.WriteLine("The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, Not(myIndex))
        Else
            Console.WriteLine("The object to search for ({0}) is at index {1}.", myObject, myIndex)
        End If
    End Sub

    Public Shared Sub PrintValues(myArr As Array)
        Dim i As Integer = 0
        Dim cols As Integer = myArr.GetLength( myArr.Rank - 1 )
        For Each o As Object In myArr
            If i < cols Then
                i += 1
            Else
                Console.WriteLine()
                i = 1
            End If
            Console.Write( vbTab + "{0}", o)
        Next o
        Console.WriteLine()
    End Sub
End Class
' This code produces the following output.
'
' The Int32 array contains the following:
'         2       3       6       7       8
' The object to search for (1) is not found. The next larger object is at index 0
'
' The object to search for (6) is at index 2.

注解

此方法不支持搜索包含负索引的数组。This method does not support searching arrays that contain negative indexes. array在调用此方法之前必须进行排序。array must be sorted before calling this method.

Array如果不包含指定的值, 则该方法返回一个负整数。If the Array does not contain the specified value, the method returns a negative integer. 可以将按位求补运算符 ( C# Not在 Visual Basic 中为) 应用于负结果, 以生成索引。You can apply the bitwise complement operator (~ in C#, Not in Visual Basic) to the negative result to produce an index. 如果此索引大于数组的上限, 则数组value中没有大于的元素。If this index is one greater than the upper bound of the array, there are no elements larger than value in the array. 否则, 它是大于的第一个元素value的索引。Otherwise, it is the index of the first element that is larger than value.

或的array每个元素都必须实现IComparable接口, 该接口用于比较。 valueEither value or every element of array must implement the IComparable interface, which is used for comparisons. array元素必须已根据IComparable实现定义的排序顺序按递增值排序; 否则, 结果可能不正确。The elements of array must already be sorted in increasing value according to the sort order defined by the IComparable implementation; otherwise, the result might be incorrect.

备注

如果valueIComparable实现IComparable 接口,则在搜索开始之前,array不会对的元素进行测试。Ifvalue does not implement the IComparable interface, the elements of array are not tested for IComparable before the search begins. 如果搜索遇到不实现IComparable的元素, 则会引发异常。An exception is thrown if the search encounters an element that does not implement IComparable.

允许重复元素。Duplicate elements are allowed. 如果包含多个等于的元素value, 则此方法只返回其中一个匹配项的索引, 而不是第一个匹配项的索引。 ArrayIf 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.

null始终可以与任何其他引用类型进行比较;因此, 与的null比较不会生成异常。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception.

备注

对于测试的每个value元素, 都将传递IComparable到适当的实现value , null即使是。For every element tested, value is passed to the appropriate IComparable implementation, even if value is null. 也就是说, 该IComparable实现确定给定元素如何与null进行比较。That is, the IComparable implementation determines how a given element compares to null.

此方法是 O ( nlog) 运算, 其中nLengtharrayThis method is an O(log n) operation, where n is the Length of array.

另请参阅

BinarySearch(Array, Object, IComparer) BinarySearch(Array, Object, IComparer) BinarySearch(Array, Object, IComparer)

使用指定 IComparer 接口,在整个一维排序数组中搜索值。Searches an entire one-dimensional sorted array for a value using the specified IComparer interface.

public:
 static int BinarySearch(Array ^ array, System::Object ^ value, System::Collections::IComparer ^ comparer);
public static int BinarySearch (Array array, object value, System.Collections.IComparer comparer);
static member BinarySearch : Array * obj * System.Collections.IComparer -> int

参数

array
Array Array Array Array

要搜索的排序一维 ArrayThe sorted one-dimensional Array to search.

value
Object Object Object Object

要搜索的对象。The object to search for.

comparer
IComparer IComparer IComparer IComparer

比较元素时要使用的 IComparer 实现。The IComparer implementation to use when comparing elements.

-or- 若为 null,则使用每个元素的 IComparable 实现。null to use the IComparable implementation of each element.

返回

如果找到 value,则为指定 array 中的指定 value 的索引;否则为负数。The index of the specified value in the specified array, if value is found; otherwise, a negative number. 如果找不到 valuevalue 小于 array 中的一个或多个元素,则返回的负数是大于 value 的第一个元素的索引的按位求补。If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. 如果找不到 valuevalue 大于 array 中的所有元素,则返回的负数是(最后一个元素的索引加 1)的按位求补。If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1). 如果使用非排序的 array 调用此方法,返回值则可能不正确并且可能会返回负数,即使 value 存在于 array 中也是如此。If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if value is present in array.

异常

array 是多维的。array is multidimensional.

comparernull,并且 value 的类型与 array的元素不兼容。comparer is null, and value is of a type that is not compatible with the elements of array.

comparernullvalue 不实现 IComparable 接口,并且搜索遇到不实现 IComparable 接口的元素。comparer is null, value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface.

注解

此方法不支持搜索包含负索引的数组。This method does not support searching arrays that contain negative indexes. array在调用此方法之前必须进行排序。array must be sorted before calling this method.

Array如果不包含指定的值, 则该方法返回一个负整数。If the Array does not contain the specified value, the method returns a negative integer. 可以将按位求补运算符 ( C# Not在 Visual Basic 中为) 应用于负结果, 以生成索引。You can apply the bitwise complement operator (~ in C#, Not in Visual Basic) to the negative result to produce an index. 如果此索引大于数组的上限, 则数组value中没有大于的元素。If this index is one greater than the upper bound of the array, there are no elements larger than value in the array. 否则, 它是大于的第一个元素value的索引。Otherwise, it is the index of the first element that is larger than value.

比较器自定义元素的比较方式。The comparer customizes how the elements are compared. 例如, 可以将System.Collections.CaseInsensitiveComparer用作比较器来执行不区分大小写的字符串搜索。For example, you can use a System.Collections.CaseInsensitiveComparer as the comparer to perform case-insensitive string searches.

如果comparerarray IComparer为, 则使用指定的实现将的元素与指定的值进行比较。 nullIf comparer is not null, the elements of array are compared to the specified value using the specified IComparer implementation. array元素必须已根据comparer定义的排序顺序按递增的值排序; 否则, 结果可能不正确。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.

如果comparer IComparablenull, 则使用由元素本身或指定的值提供的实现进行比较。Ifcomparer is null, the comparison is done using the IComparable implementation provided by the element itself or by the specified value. array元素必须已根据IComparable实现定义的排序顺序按递增值排序; 否则, 结果可能不正确。The elements of array must already be sorted in increasing value according to the sort order defined by the IComparable implementation; otherwise, the result might be incorrect.

备注

如果comparernull IComparablearray未实现接口,则在搜索开始之前,不会对的元素进行测试。IComparable valueIf comparer is null and value does not implement the IComparable interface, the elements of array are not tested for IComparable before the search begins. 如果搜索遇到不实现IComparable的元素, 则会引发异常。An exception is thrown if the search encounters an element that does not implement IComparable.

允许重复元素。Duplicate elements are allowed. 如果包含多个等于的元素value, 则此方法只返回其中一个匹配项的索引, 而不是第一个匹配项的索引。 ArrayIf 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.

null始终可以与任何其他引用类型进行比较;因此, 与的null比较不会生成异常。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception.

备注

对于测试的每个value元素, 都将传递IComparable到适当的实现value , null即使是。For every element tested, value is passed to the appropriate IComparable implementation, even if value is null. 也就是说, 该IComparable实现确定给定元素如何与null进行比较。That is, the IComparable implementation determines how a given element compares to null.

此方法是 O ( nlog) 运算, 其中nLengtharrayThis method is an O(log n) operation, where n is the Length of array.

另请参阅

BinarySearch(Array, Int32, Int32, Object) BinarySearch(Array, Int32, Int32, Object) BinarySearch(Array, Int32, Int32, Object)

使用由一维排序数组中每个元素和指定的值实现的 IComparable 接口,在该数组的一个元素范围内搜索值。Searches a range of elements in a one-dimensional sorted array for a value, using the IComparable interface implemented by each element of the array and by the specified value.

public:
 static int BinarySearch(Array ^ array, int index, int length, System::Object ^ value);
public static int BinarySearch (Array array, int index, int length, object value);
static member BinarySearch : Array * int * int * obj -> int

参数

array
Array Array Array Array

要搜索的排序一维 ArrayThe sorted one-dimensional Array to search.

index
Int32 Int32 Int32 Int32

要搜索的范围的起始索引。The starting index of the range to search.

length
Int32 Int32 Int32 Int32

要搜索的范围的长度。The length of the range to search.

value
Object Object Object Object

要搜索的对象。The object to search for.

返回

如果找到 value,则为指定 array 中的指定 value 的索引;否则为负数。The index of the specified value in the specified array, if value is found; otherwise, a negative number. 如果找不到 valuevalue 小于 array 中的一个或多个元素,则返回的负数是大于 value 的第一个元素的索引的按位求补。If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. 如果找不到 valuevalue 大于 array 中的所有元素,则返回的负数是(最后一个元素的索引加 1)的按位求补。If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1). 如果使用非排序的 array 调用此方法,返回值则可能不正确并且可能会返回负数,即使 value 存在于 array 中也是如此。If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if value is present in array.

异常

array 是多维的。array is multidimensional.

index 小于 array 的下限。index is less than the lower bound of array.

-or- length 小于零。length is less than zero.

indexlength 未在 array 中指定有效范围。index and length do not specify a valid range in array.

-or- value 的类型与 array 的元素不兼容。value is of a type that is not compatible with the elements of array.

value 不实现 IComparable 接口,并且搜索遇到不实现 IComparable 接口的元素。value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface.

注解

此方法不支持搜索包含负索引的数组。This method does not support searching arrays that contain negative indexes. array在调用此方法之前必须进行排序。array must be sorted before calling this method.

Array如果不包含指定的值, 则该方法返回一个负整数。If the Array does not contain the specified value, the method returns a negative integer. 可以将按位求补运算符 ( C# Not在 Visual Basic 中为) 应用于负结果, 以生成索引。You can apply the bitwise complement operator (~ in C#, Not in Visual Basic) to the negative result to produce an index. 如果此索引大于数组的上限, 则数组value中没有大于的元素。If this index is one greater than the upper bound of the array, there are no elements larger than value in the array. 否则, 它是大于的第一个元素value的索引。Otherwise, it is the index of the first element that is larger than value.

或的array每个元素都必须实现IComparable接口, 该接口用于比较。 valueEither value or every element of array must implement the IComparable interface, which is used for comparisons. array元素必须已根据IComparable实现定义的排序顺序按递增值排序; 否则, 结果可能不正确。The elements of array must already be sorted in increasing value according to the sort order defined by the IComparable implementation; otherwise, the result might be incorrect.

备注

如果valueIComparable实现IComparable 接口,则在搜索开始之前,array不会对的元素进行测试。If value does not implement the IComparable interface, the elements of array are not tested for IComparable before the search begins. 如果搜索遇到不实现IComparable的元素, 则会引发异常。An exception is thrown if the search encounters an element that does not implement IComparable.

允许重复元素。Duplicate elements are allowed. 如果包含多个等于的元素value, 则此方法只返回其中一个匹配项的索引, 而不是第一个匹配项的索引。 ArrayIf 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.

null始终可以与任何其他引用类型进行比较;因此, 与的null比较不会生成异常。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception.

备注

对于测试的每个value元素, 都将传递IComparable到适当的实现value , null即使是。For every element tested, value is passed to the appropriate IComparable implementation, even if value is null. 也就是说, 该IComparable实现确定给定元素如何与null进行比较。That is, the IComparable implementation determines how a given element compares to null.

此方法的运算复杂度为 O n(log), n其中length, 为。This method is an O(log n) operation, where n is length.

另请参阅

BinarySearch(Array, Int32, Int32, Object, IComparer) BinarySearch(Array, Int32, Int32, Object, IComparer) BinarySearch(Array, Int32, Int32, Object, IComparer)

使用指定 IComparer 接口,在一维排序数组的某个元素范围中搜索值。Searches a range of elements in a one-dimensional sorted array for a value, using the specified IComparer interface.

public:
 static int BinarySearch(Array ^ array, int index, int length, System::Object ^ value, System::Collections::IComparer ^ comparer);
public static int BinarySearch (Array array, int index, int length, object value, System.Collections.IComparer comparer);
static member BinarySearch : Array * int * int * obj * System.Collections.IComparer -> int

参数

array
Array Array Array Array

要搜索的排序一维 ArrayThe sorted one-dimensional Array to search.

index
Int32 Int32 Int32 Int32

要搜索的范围的起始索引。The starting index of the range to search.

length
Int32 Int32 Int32 Int32

要搜索的范围的长度。The length of the range to search.

value
Object Object Object Object

要搜索的对象。The object to search for.

comparer
IComparer IComparer IComparer IComparer

比较元素时要使用的 IComparer 实现。The IComparer implementation to use when comparing elements.

- 或 --or- 若为 null,则使用每个元素的 IComparable 实现。null to use the IComparable implementation of each element.

返回

如果找到 value,则为指定 array 中的指定 value 的索引;否则为负数。The index of the specified value in the specified array, if value is found; otherwise, a negative number. 如果找不到 valuevalue 小于 array 中的一个或多个元素,则返回的负数是大于 value 的第一个元素的索引的按位求补。If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. 如果找不到 valuevalue 大于 array 中的所有元素,则返回的负数是(最后一个元素的索引加 1)的按位求补。If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1). 如果使用非排序的 array 调用此方法,返回值则可能不正确并且可能会返回负数,即使 value 存在于 array 中也是如此。If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if value is present in array.

异常

array 是多维的。array is multidimensional.

index 小于 array 的下限。index is less than the lower bound of array.

-or- length 小于零。length is less than zero.

indexlength 未在 array 中指定有效范围。index and length do not specify a valid range in array.

-or- comparernull,并且 value 的类型与 array 的元素不兼容。comparer is null, and value is of a type that is not compatible with the elements of array.

comparernullvalue 不实现 IComparable 接口,并且搜索遇到不实现 IComparable 接口的元素。comparer is null, value does not implement the IComparable interface, and the search encounters an element that does not implement the IComparable interface.

注解

此方法不支持搜索包含负索引的数组。This method does not support searching arrays that contain negative indexes. array在调用此方法之前必须进行排序。array must be sorted before calling this method.

Array如果不包含指定的值, 则该方法返回一个负整数。If the Array does not contain the specified value, the method returns a negative integer. 可以将按位求补运算符 ( C# Not在 Visual Basic 中为) 应用于负结果, 以生成索引。You can apply the bitwise complement operator (~ in C#, Not in Visual Basic) to the negative result to produce an index. 如果此索引大于数组的上限, 则数组value中没有大于的元素。If this index is one greater than the upper bound of the array, there are no elements larger than value in the array. 否则, 它是大于的第一个元素value的索引。Otherwise, it is the index of the first element that is larger than value.

比较器自定义元素的比较方式。The comparer customizes how the elements are compared. 例如, 可以将System.Collections.CaseInsensitiveComparer用作比较器来执行不区分大小写的字符串搜索。For example, you can use a System.Collections.CaseInsensitiveComparer as the comparer to perform case-insensitive string searches.

如果comparerarray IComparer为, 则使用指定的实现将的元素与指定的值进行比较。 nullIf comparer is not null, the elements of array are compared to the specified value using the specified IComparer implementation. array元素必须已根据comparer定义的排序顺序按递增的值排序; 否则, 结果可能不正确。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.

如果comparer IComparablenull, 则使用由元素本身或指定的值提供的实现进行比较。If comparer is null, the comparison is done using the IComparable implementation provided by the element itself or by the specified value. array元素必须已根据IComparable实现定义的排序顺序按递增值排序; 否则, 结果可能不正确。The elements of array must already be sorted in increasing value according to the sort order defined by the IComparable implementation; otherwise, the result might be incorrect.

备注

如果comparernull IComparablearray未实现接口,则在搜索开始之前,不会对的元素进行测试。IComparable valueIf comparer is null and value does not implement the IComparable interface, the elements of array are not tested for IComparable before the search begins. 如果搜索遇到不实现IComparable的元素, 则会引发异常。An exception is thrown if the search encounters an element that does not implement IComparable.

允许重复元素。Duplicate elements are allowed. 如果包含多个等于的元素value, 则此方法只返回其中一个匹配项的索引, 而不是第一个匹配项的索引。 ArrayIf 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.

null始终可以与任何其他引用类型进行比较;因此, 使用IComparablenull , 与的比较不会生成异常。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception when using IComparable.

备注

对于测试的每个value元素, 都将传递IComparable到适当的实现value , null即使是。For every element tested, value is passed to the appropriate IComparable implementation, even if value is null. 也就是说, 该IComparable实现确定给定元素如何与null进行比较。That is, the IComparable implementation determines how a given element compares to null.

此方法的运算复杂度为 O n(log), n其中length, 为。This method is an O(log n) operation, where n is length.

另请参阅

BinarySearch<T>(T[], T) BinarySearch<T>(T[], T) BinarySearch<T>(T[], T) BinarySearch<T>(T[], T)

使用由 Array 中每个元素和指定对象实现的 IComparable<T> 泛型接口,在整个一维排序数组中搜索特定元素。Searches an entire one-dimensional sorted array for a specific element, using the IComparable<T> generic interface implemented by each element of the Array and by the specified object.

public:
generic <typename T>
 static int BinarySearch(cli::array <T> ^ array, T value);
public static int BinarySearch<T> (T[] array, T value);
static member BinarySearch : 'T[] * 'T -> int
Public Shared Function BinarySearch(Of T) (array As T(), value As T) As Integer

类型参数

T

数组元素的类型。The type of the elements of the array.

参数

array
T[]

要搜索的从零开始的一维排序 ArrayThe sorted one-dimensional, zero-based Array to search.

value
T T T T

要搜索的对象。The object to search for.

返回

如果找到 value,则为指定 array 中的指定 value 的索引;否则为负数。The index of the specified value in the specified array, if value is found; otherwise, a negative number. 如果找不到 valuevalue 小于 array 中的一个或多个元素,则返回的负数是大于 value 的第一个元素的索引的按位求补。If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. 如果找不到 valuevalue 大于 array 中的所有元素,则返回的负数是(最后一个元素的索引加 1)的按位求补。If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1). 如果使用非排序的 array 调用此方法,返回值则可能不正确并且可能会返回负数,即使 value 存在于 array 中也是如此。If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if value is present in array.

异常

示例

下面的代码示例演示Sort<T>(T[])泛型方法重载BinarySearch<T>(T[], T)和泛型方法重载。The following code example demonstrates the Sort<T>(T[]) generic method overload and the BinarySearch<T>(T[], T) generic method overload. 创建一个字符串数组, 无特定顺序。An array of strings is created, in no particular order.

显示、排序并再次显示数组。The array is displayed, sorted, and displayed again. 若要使用BinarySearch方法, 必须对数组进行排序。Arrays must be sorted in order to use the BinarySearch method.

备注

Sort和泛型方法的BinarySearch调用与对其非泛型方法的调用没有任何区别, 因为 Visual Basic、 C#和C++从第一个参数的类型推断泛型类型参数的类型.The calls to the Sort and BinarySearch 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. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

然后, 使用泛型方法重载搜索两个字符串, 一个字符串不在数组中, 另一个是。 BinarySearch<T>(T[], T)The BinarySearch<T>(T[], T) generic method overload is then used to search for two strings, one that is not in the array and one that is. BinarySearch方法的数组和返回值将传递ShowWhere给泛型方法, 该方法显示索引值 (如果找到该字符串), 否则为搜索字符串在数组中所处的元素。The array and the return value of the BinarySearch 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. 如果字符串不在数组中, 则该索引为负, 因此该ShowWhere方法采用按位求补 ( C#和中的 ~ 运算符C++, XorVisual Basic 中为-1) 以获取列表中较大的第一个元素的索引。比搜索字符串多。The index is negative if the string is not in 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.

using namespace System;
using namespace System::Collections::Generic;

generic<typename T> void ShowWhere(array<T>^ arr, 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;

        Console::Write("Not found. Sorts between: ");

        if (index == 0)
            Console::Write("beginning of array and ");
        else
            Console::Write("{0} and ", arr[index-1]);

        if (index == arr->Length)
            Console::WriteLine("end of array.");
        else
            Console::WriteLine("{0}.", arr[index]);
    }
    else
    {
        Console::WriteLine("Found at index {0}.", index);
    }
};

void main()
{
    array<String^>^ dinosaurs = {"Pachycephalosaurus", 
                                 "Amargasaurus", 
                                 "Tyrannosaurus", 
                                 "Mamenchisaurus", 
                                 "Deinonychus", 
                                 "Edmontosaurus"};

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nSort");
    Array::Sort(dinosaurs);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nBinarySearch for 'Coelophysis':");
    int index = Array::BinarySearch(dinosaurs, "Coelophysis");
    ShowWhere(dinosaurs, index);

    Console::WriteLine("\nBinarySearch for 'Tyrannosaurus':");
    index = Array::BinarySearch(dinosaurs, "Tyrannosaurus");
    ShowWhere(dinosaurs, index);
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

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

BinarySearch for 'Tyrannosaurus':
Found at index 5.
 */
using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {"Pachycephalosaurus", 
                              "Amargasaurus", 
                              "Tyrannosaurus", 
                              "Mamenchisaurus", 
                              "Deinonychus", 
                              "Edmontosaurus"};

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nSort");
        Array.Sort(dinosaurs);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nBinarySearch for 'Coelophysis':");
        int index = Array.BinarySearch(dinosaurs, "Coelophysis");
        ShowWhere(dinosaurs, index);

        Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus");
        ShowWhere(dinosaurs, index);
    }

    private static void ShowWhere<T>(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;

            Console.Write("Not found. Sorts between: ");

            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index-1]);

            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

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

BinarySearch for 'Tyrannosaurus':
Found at index 5.
 */
Imports System
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main()

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

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

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

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

        Console.WriteLine(vbLf & _
            "BinarySearch for 'Coelophysis':")
        Dim index As Integer = _
            Array.BinarySearch(dinosaurs, "Coelophysis")
        ShowWhere(dinosaurs, index)

        Console.WriteLine(vbLf & _
            "BinarySearch for 'Tyrannosaurus':")
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus")
        ShowWhere(dinosaurs, index)

    End Sub

    Private Shared Sub ShowWhere(Of T) _
        (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

            Console.Write("Not found. Sorts between: ")

            If index = 0 Then
                Console.Write("beginning of array and ")
            Else
                Console.Write("{0} and ", array(index - 1))
            End If 

            If index = array.Length Then
                Console.WriteLine("end of array.")
            Else
                Console.WriteLine("{0}.", array(index))
            End If 
        Else
            Console.WriteLine("Found at index {0}.", index)
        End If

    End Sub

End Class

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

注解

此方法不支持搜索包含负索引的数组。This method does not support searching arrays that contain negative indexes. array在调用此方法之前必须进行排序。array must be sorted before calling this method.

如果array不包含指定的值, 则该方法返回一个负整数。If array does not contain the specified value, the method returns a negative integer. 可以将按位求补运算符 ( C# Not在 Visual Basic 中为) 应用于负结果, 以生成索引。You can apply the bitwise complement operator (~ in C#, Not in Visual Basic) to the negative result to produce an index. 如果此索引等于数组的大小, 则数组value中没有大于的元素。If this index is equal to the size of the array, there are no elements larger than value in the array. 否则, 它是大于的第一个元素value的索引。Otherwise, it is the index of the first element that is larger than value.

T必须实现IComparable<T>用于比较的泛型接口。T must implement the IComparable<T> generic interface, which is used for comparisons. array元素必须已根据IComparable<T>实现定义的排序顺序按递增值排序; 否则, 结果可能不正确。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.

允许重复元素。Duplicate elements are allowed. 如果包含多个等于的元素value, 则此方法只返回其中一个匹配项的索引, 而不是第一个匹配项的索引。 ArrayIf 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.

null始终可以与任何其他引用类型进行比较;因此, 与的null比较不会生成异常。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception.

备注

对于测试的每个value元素, 都将传递IComparable<T>到适当的实现value , null即使是。For every element tested, value is passed to the appropriate IComparable<T> implementation, even if value is null. 也就是说, 该IComparable<T>实现确定给定元素如何与null进行比较。That is, the IComparable<T> implementation determines how a given element compares to null.

此方法是 O ( nlog) 运算, 其中nLengtharrayThis method is an O(log n) operation, where n is the Length of array.

另请参阅

BinarySearch<T>(T[], T, IComparer<T>) BinarySearch<T>(T[], T, IComparer<T>) BinarySearch<T>(T[], T, IComparer<T>) BinarySearch<T>(T[], T, IComparer<T>)

使用指定 IComparer<T> 泛型接口,在整个一维排序数组中搜索值。Searches an entire one-dimensional sorted array for a value using the specified IComparer<T> generic interface.

public:
generic <typename T>
 static int BinarySearch(cli::array <T> ^ array, T value, System::Collections::Generic::IComparer<T> ^ comparer);
public static int BinarySearch<T> (T[] array, T value, System.Collections.Generic.IComparer<T> comparer);
static member BinarySearch : 'T[] * 'T * System.Collections.Generic.IComparer<'T> -> int
Public Shared Function BinarySearch(Of T) (array As T(), value As T, comparer As IComparer(Of T)) As Integer

类型参数

T

数组元素的类型。The type of the elements of the array.

参数

array
T[]

要搜索的从零开始的一维排序 ArrayThe sorted one-dimensional, zero-based Array to search.

value
T T T T

要搜索的对象。The object to search for.

comparer
IComparer<T> IComparer<T> IComparer<T> IComparer<T>

比较元素时要使用的 IComparer<T> 实现。The IComparer<T> implementation to use when comparing elements.

-or- 若为 null,则使用每个元素的 IComparable<T> 实现。null to use the IComparable<T> implementation of each element.

返回

如果找到 value,则为指定 array 中的指定 value 的索引;否则为负数。The index of the specified value in the specified array, if value is found; otherwise, a negative number. 如果找不到 valuevalue 小于 array 中的一个或多个元素,则返回的负数是大于 value 的第一个元素的索引的按位求补。If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. 如果找不到 valuevalue 大于 array 中的所有元素,则返回的负数是(最后一个元素的索引加 1)的按位求补。If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1). 如果使用非排序的 array 调用此方法,返回值则可能不正确并且可能会返回负数,即使 value 存在于 array 中也是如此。If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if value is present in array.

异常

comparernull,并且 value 的类型与 array 的元素不兼容。comparer is null, and value is of a type that is not compatible with the elements of array.

comparernull,并且 T 不实现 IComparable<T> 泛型接口comparer is null, and T does not implement the IComparable<T> generic interface

示例

下面的示例演示Sort<T>(T[], IComparer<T>)泛型方法重载BinarySearch<T>(T[], T, IComparer<T>)和泛型方法重载。The following example demonstrates the Sort<T>(T[], IComparer<T>) generic method overload and the BinarySearch<T>(T[], T, IComparer<T>) generic method overload.

此代码示例定义了一个名为ReverseCompare的字符串的替代比较器, 该比较器实现了IComparer<string> ( C++IComparer(Of String)在 Visual Basic IComparer<String^>中的 Visual) 泛型接口。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. 比较器调用CompareTo(String)方法, 并反转比较数的顺序, 以便字符串排序为高到低而不是低到高。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. 若要使用BinarySearch方法, 必须对数组进行排序。Arrays must be sorted in order to use the BinarySearch method.

备注

Sort<T>(T[], IComparer<T>)和泛型方法的BinarySearch<T>(T[], T, IComparer<T>)调用与对其非泛型方法的调用没有任何区别, 因为 Visual Basic、 C#和C++从第一个参数的类型推断泛型类型参数的类型.The calls to the Sort<T>(T[], IComparer<T>) and BinarySearch<T>(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. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

然后, 使用泛型方法重载搜索两个字符串, 一个字符串不在数组中, 另一个是。 BinarySearch<T>(T[], T, IComparer<T>)The BinarySearch<T>(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. BinarySearch<T>(T[], T, IComparer<T>)方法的数组和返回值将传递ShowWhere给泛型方法, 该方法显示索引值 (如果找到该字符串), 否则为搜索字符串在数组中所处的元素。The array and the return value of the BinarySearch<T>(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. 如果字符串不是 n 数组, 则该索引为负, 因此该ShowWhere方法采用按位求补 ( C#和中的 ~ 运算符C++, Xor Visual Basic 中为-1) 以获取列表中大于的第一个元素的索引。搜索字符串。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.

using namespace System;
using namespace System::Collections::Generic;

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

generic<typename T> void ShowWhere(array<T>^ arr, 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;

        Console::Write("Not found. Sorts between: ");

        if (index == 0)
            Console::Write("beginning of array and ");
        else
            Console::Write("{0} and ", arr[index-1]);

        if (index == arr->Length)
            Console::WriteLine("end of array.");
        else
            Console::WriteLine("{0}.", arr[index]);
    }
    else
    {
        Console::WriteLine("Found at index {0}.", index);
    }
};

void main()
{
    array<String^>^ dinosaurs = {"Pachycephalosaurus", 
                                 "Amargasaurus", 
                                 "Tyrannosaurus", 
                                 "Mamenchisaurus", 
                                 "Deinonychus", 
                                 "Edmontosaurus"};

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

    Console::WriteLine("\nSort");
    Array::Sort(dinosaurs, rc);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nBinarySearch for 'Coelophysis':");
    int index = Array::BinarySearch(dinosaurs, "Coelophysis", rc);
    ShowWhere(dinosaurs, index);

    Console::WriteLine("\nBinarySearch for 'Tyrannosaurus':");
    index = Array::BinarySearch(dinosaurs, "Tyrannosaurus", rc);
    ShowWhere(dinosaurs, index);
}

/* 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 Main()
    {
        string[] dinosaurs = {"Pachycephalosaurus", 
                              "Amargasaurus", 
                              "Tyrannosaurus", 
                              "Mamenchisaurus", 
                              "Deinonychus", 
                              "Edmontosaurus"};

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort");
        Array.Sort(dinosaurs, rc);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nBinarySearch for 'Coelophysis':");
        int index = Array.BinarySearch(dinosaurs, "Coelophysis", rc);
        ShowWhere(dinosaurs, index);

        Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc);
        ShowWhere(dinosaurs, index);
    }

    private static void ShowWhere<T>(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;

            Console.Write("Not found. Sorts between: ");

            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index-1]);

            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}

/* 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.
 */
Imports System
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 Main()

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

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

        Dim rc As New ReverseComparer()

        Console.WriteLine(vbLf & "Sort")
        Array.Sort(dinosaurs, rc)

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

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

        Console.WriteLine(vbLf & _
            "BinarySearch for 'Tyrannosaurus':")
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
        ShowWhere(dinosaurs, index)

    End Sub

    Private Shared Sub ShowWhere(Of T) _
        (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

            Console.Write("Not found. Sorts between: ")

            If index = 0 Then
                Console.Write("beginning of array and ")
            Else
                Console.Write("{0} and ", array(index - 1))
            End If 

            If index = array.Length Then
                Console.WriteLine("end of array.")
            Else
                Console.WriteLine("{0}.", array(index))
            End If 
        Else
            Console.WriteLine("Found at index {0}.", index)
        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.

注解

此方法不支持搜索包含负索引的数组。This method does not support searching arrays that contain negative indexes. array在调用此方法之前必须进行排序。array must be sorted before calling this method.

Array如果不包含指定的值, 则该方法返回一个负整数。If the Array does not contain the specified value, the method returns a negative integer. 可以将按位求补运算符 ( C# Not在 Visual Basic 中为) 应用于负结果, 以生成索引。You can apply the bitwise complement operator (~ in C#, Not in Visual Basic) to the negative result to produce an index. 如果此索引等于数组的大小, 则数组value中没有大于的元素。If this index is equal to the size of the array, there are no elements larger than value in the array. 否则, 它是大于的第一个元素value的索引。Otherwise, it is the index of the first element that is larger than value.

比较器自定义元素的比较方式。The comparer customizes how the elements are compared. 例如, 可以将System.Collections.CaseInsensitiveComparer用作比较器来执行不区分大小写的字符串搜索。For example, you can use a System.Collections.CaseInsensitiveComparer as the comparer to perform case-insensitive string searches.

如果comparerarray IComparer<T>为, 则使用指定的泛型接口实现将的元素与指定的值进行比较。 nullIf comparer is not null, the elements of array are compared to the specified value using the specified IComparer<T> generic interface implementation. array元素必须已根据comparer定义的排序顺序按递增的值排序; 否则, 结果可能不正确。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.

如果comparer IComparable<T>null, 则使用提供T的泛型接口实现进行比较。If comparer is null, the comparison is done using the IComparable<T> generic interface implementation provided by T. array元素必须已根据IComparable<T>实现定义的排序顺序按递增值排序; 否则, 结果可能不正确。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.

备注

如果comparernull IComparable<T> ,并且value不实现array泛型接口, 则在搜索开始之前, 不会测试IComparable<T>的元素。If comparer is null and value does not implement the IComparable<T> generic interface, the elements of array are not tested for IComparable<T> before the search begins. 如果搜索遇到不实现IComparable<T>的元素, 则会引发异常。An exception is thrown if the search encounters an element that does not implement IComparable<T>.

允许重复元素。Duplicate elements are allowed. 如果包含多个等于的元素value, 则此方法只返回其中一个匹配项的索引, 而不是第一个匹配项的索引。 ArrayIf 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.

null始终可以与任何其他引用类型进行比较;因此, 与的null比较不会生成异常。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception.

备注

对于测试的每个value元素, 都将传递IComparable<T>到适当的实现value , null即使是。For every element tested, value is passed to the appropriate IComparable<T> implementation, even if value is null. 也就是说, 该IComparable<T>实现确定给定元素如何与null进行比较。That is, the IComparable<T> implementation determines how a given element compares to null.

此方法是 O ( nlog) 运算, 其中nLengtharrayThis method is an O(log n) operation, where n is the Length of array.

另请参阅

BinarySearch<T>(T[], Int32, Int32, T) BinarySearch<T>(T[], Int32, Int32, T) BinarySearch<T>(T[], Int32, Int32, T) BinarySearch<T>(T[], Int32, Int32, T)

使用由 Array 中每个元素和指定值实现的 IComparable<T> 泛型接口,在一维排序数组的某个元素范围中搜索值。Searches a range of elements in a one-dimensional sorted array for a value, using the IComparable<T> generic interface implemented by each element of the Array and by the specified value.

public:
generic <typename T>
 static int BinarySearch(cli::array <T> ^ array, int index, int length, T value);
public static int BinarySearch<T> (T[] array, int index, int length, T value);
static member BinarySearch : 'T[] * int * int * 'T -> int
Public Shared Function BinarySearch(Of T) (array As T(), index As Integer, length As Integer, value As T) As Integer

类型参数

T

数组元素的类型。The type of the elements of the array.

参数

array
T[]

要搜索的从零开始的一维排序 ArrayThe sorted one-dimensional, zero-based Array to search.

index
Int32 Int32 Int32 Int32

要搜索的范围的起始索引。The starting index of the range to search.

length
Int32 Int32 Int32 Int32

要搜索的范围的长度。The length of the range to search.

value
T T T T

要搜索的对象。The object to search for.

返回

如果找到 value,则为指定 array 中的指定 value 的索引;否则为负数。The index of the specified value in the specified array, if value is found; otherwise, a negative number. 如果找不到 valuevalue 小于 array 中的一个或多个元素,则返回的负数是大于 value 的第一个元素的索引的按位求补。If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. 如果找不到 valuevalue 大于 array 中的所有元素,则返回的负数是(最后一个元素的索引加 1)的按位求补。If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1). 如果使用非排序的 array 调用此方法,返回值则可能不正确并且可能会返回负数,即使 value 存在于 array 中也是如此。If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if value is present in array.

异常

index 小于 array 的下限。index is less than the lower bound of array.

-or- length 小于零。length is less than zero.

indexlength 未在 array 中指定有效范围。index and length do not specify a valid range in array.

- 或 --or- value 的类型与 array 的元素不兼容。value is of a type that is not compatible with the elements of array.

注解

此方法不支持搜索包含负索引的数组。This method does not support searching arrays that contain negative indexes. array在调用此方法之前必须进行排序。array must be sorted before calling this method.

如果数组不包含指定的值, 则该方法返回一个负整数。If the array does not contain the specified value, the method returns a negative integer. 可以将按位求补运算符 ( C# Not在 Visual Basic 中为) 应用于负结果, 以生成索引。You can apply the bitwise complement operator (~ in C#, Not in Visual Basic) to the negative result to produce an index. 如果此索引等于数组的大小, 则数组value中没有大于的元素。If this index is equal to the size of the array, there are no elements larger than value in the array. 否则, 它是大于的第一个元素value的索引。Otherwise, it is the index of the first element that is larger than value.

T必须实现IComparable<T>用于比较的泛型接口。T must implement the IComparable<T> generic interface, which is used for comparisons. array元素必须已根据IComparable<T>实现定义的排序顺序按递增值排序; 否则, 结果可能不正确。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.

允许重复元素。Duplicate elements are allowed. 如果包含多个等于的元素value, 则此方法只返回其中一个匹配项的索引, 而不是第一个匹配项的索引。 ArrayIf 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.

null始终可以与任何其他引用类型进行比较;因此, 与的null比较不会生成异常。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception.

备注

对于测试的每个value元素, 都将传递IComparable<T>到适当的实现value , null即使是。For every element tested, value is passed to the appropriate IComparable<T> implementation, even if value is null. 也就是说, 该IComparable<T>实现确定给定元素如何与null进行比较。That is, the IComparable<T> implementation determines how a given element compares to null.

此方法的运算复杂度为 O n(log), n其中length, 为。This method is an O(log n) operation, where n is length.

另请参阅

BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)

使用指定 IComparer<T> 泛型接口,在一维排序数组的某个元素范围中搜索值。Searches a range of elements in a one-dimensional sorted array for a value, using the specified IComparer<T> generic interface.

public:
generic <typename T>
 static int BinarySearch(cli::array <T> ^ array, int index, int length, T value, System::Collections::Generic::IComparer<T> ^ comparer);
public static int BinarySearch<T> (T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer);
static member BinarySearch : 'T[] * int * int * 'T * System.Collections.Generic.IComparer<'T> -> int
Public Shared Function BinarySearch(Of T) (array As T(), index As Integer, length As Integer, value As T, comparer As IComparer(Of T)) As Integer

类型参数

T

数组元素的类型。The type of the elements of the array.

参数

array
T[]

要搜索的从零开始的一维排序 ArrayThe sorted one-dimensional, zero-based Array to search.

index
Int32 Int32 Int32 Int32

要搜索的范围的起始索引。The starting index of the range to search.

length
Int32 Int32 Int32 Int32

要搜索的范围的长度。The length of the range to search.

value
T T T T

要搜索的对象。The object to search for.

comparer
IComparer<T> IComparer<T> IComparer<T> IComparer<T>

比较元素时要使用的 IComparer<T> 实现。The IComparer<T> implementation to use when comparing elements.

- 或 --or- 若为 null,则使用每个元素的 IComparable<T> 实现。null to use the IComparable<T> implementation of each element.

返回

如果找到 value,则为指定 array 中的指定 value 的索引;否则为负数。The index of the specified value in the specified array, if value is found; otherwise, a negative number. 如果找不到 valuevalue 小于 array 中的一个或多个元素,则返回的负数是大于 value 的第一个元素的索引的按位求补。If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. 如果找不到 valuevalue 大于 array 中的所有元素,则返回的负数是(最后一个元素的索引加 1)的按位求补。If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1). 如果使用非排序的 array 调用此方法,返回值则可能不正确并且可能会返回负数,即使 value 存在于 array 中也是如此。If this method is called with a non-sorted array, the return value can be incorrect and a negative number could be returned, even if value is present in array.

异常

index 小于 array 的下限。index is less than the lower bound of array.

-or- length 小于零。length is less than zero.

indexlength 未在 array 中指定有效范围。index and length do not specify a valid range in array.

-or- comparernull,并且 value 的类型与 array 的元素不兼容。comparer is null, and value is of a type that is not compatible with the elements of array.

comparernull,并且 T 不实现 IComparable<T> 泛型接口。comparer is null, and T does not implement the IComparable<T> generic interface.

注解

此方法不支持搜索包含负索引的数组。This method does not support searching arrays that contain negative indexes. array在调用此方法之前必须进行排序。array must be sorted before calling this method.

如果数组不包含指定的值, 则该方法返回一个负整数。If the array does not contain the specified value, the method returns a negative integer. 可以将按位求补运算符 ( C# Not在 Visual Basic 中为) 应用于负结果, 以生成索引。You can apply the bitwise complement operator (~ in C#, Not in Visual Basic) to the negative result to produce an index. 如果此索引等于数组的大小, 则数组value中没有大于的元素。If this index is equal to the size of the array, there are no elements larger than value in the array. 否则, 它是大于的第一个元素value的索引。Otherwise, it is the index of the first element that is larger than value.

比较器自定义元素的比较方式。The comparer customizes how the elements are compared. 例如, 可以将System.Collections.CaseInsensitiveComparer用作比较器来执行不区分大小写的字符串搜索。For example, you can use a System.Collections.CaseInsensitiveComparer as the comparer to perform case-insensitive string searches.

如果comparerarray IComparer<T>为, 则使用指定的泛型接口实现将的元素与指定的值进行比较。 nullIf comparer is not null, the elements of array are compared to the specified value using the specified IComparer<T> generic interface implementation. array元素必须已根据comparer定义的排序顺序按递增的值排序; 否则, 结果可能不正确。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.

如果comparer IComparable<T> Tnull, 则使用为类型提供的泛型接口实现来完成比较。If comparer is null, the comparison is done using the IComparable<T> generic interface implementation provided for type T. array元素必须已根据IComparable<T>实现定义的排序顺序按递增值排序; 否则, 结果可能不正确。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.

允许重复元素。Duplicate elements are allowed. 如果包含多个等于的元素value, 则此方法只返回其中一个匹配项的索引, 而不是第一个匹配项的索引。 ArrayIf 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.

null始终可以与任何其他引用类型进行比较;因此, 使用IComparable<T>null , 与的比较不会生成异常。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception when using IComparable<T>.

备注

对于测试的每个value元素, 都将传递IComparable<T>到适当的实现value , null即使是。For every element tested, value is passed to the appropriate IComparable<T> implementation, even if value is null. 也就是说, 该IComparable<T>实现确定给定元素如何与null进行比较。That is, the IComparable<T> implementation determines how a given element compares to null.

此方法的运算复杂度为 O n(log), n其中length, 为。This method is an O(log n) operation, where n is length.

另请参阅

适用于