Array.BinarySearch 方法

定義

使用二進位搜尋演算法,在一維且已排序的 Array 中搜尋值。Searches a one-dimensional sorted Array for a value, using a binary search algorithm.

多載

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)

使用指定的 IComparer 介面,在整個一維已排序的陣列中搜尋值。Searches an entire one-dimensional sorted array for a value using the specified IComparer interface.

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)

使用指定的 IComparer 介面,在已排序的一維陣列內某範圍的項目中搜尋值。Searches a range of elements in a one-dimensional sorted array for a value, using the specified IComparer interface.

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

使用指定的 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)

使用 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>)

使用指定的 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)

使用陣列每個項目和指定物件所實作的 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

要搜尋之已排序的一維 ArrayThe sorted one-dimensional Array to search.

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

例外狀況

arraynullarray is null.

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.
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. 在呼叫這個方法之前,必須先排序 arrayarray must be sorted before calling this method.

如果 Array 不包含指定的值,則此方法會傳回負整數。If the Array does not contain the specified value, the method returns a negative integer. 您可以將位補數運算子(~ in 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.

valuearray 的每個元素都必須執行 IComparable 介面,以用於比較。Either 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.

注意

如果value 不會執行 IComparable 介面,則在開始搜尋之前,不會針對 IComparable 測試 array 的元素。Ifvalue does not implement the IComparable interface, the elements of array are not tested for IComparable before the search begins. 如果搜尋遇到不會執行 IComparable的專案,則會擲回例外狀況(exception)。An exception is thrown if the search encounters an element that does not implement IComparable.

允許重複的元素。Duplicate elements are allowed. 如果 Array 包含多個等於 value的元素,此方法只會傳回其中一個出現專案的索引,而不一定是第一個發生的。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.

null 一律可以與任何其他參考型別進行比較;因此,與 null 的比較不會產生例外狀況。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception.

注意

針對每個測試的專案,value 都會傳遞至適當的 IComparable 實作為,即使 value nullFor 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 (log n)運算,其中 narrayLengthThis method is an O(log n) operation, where n is the Length of array.

另請參閱

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

要搜尋之已排序的一維 ArrayThe sorted one-dimensional Array to search.

value
Object

要搜尋的物件。The object to search for.

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

例外狀況

arraynullarray is null.

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. 在呼叫這個方法之前,必須先排序 arrayarray must be sorted before calling this method.

如果 Array 不包含指定的值,則此方法會傳回負整數。If the Array does not contain the specified value, the method returns a negative integer. 您可以將位補數運算子(~ in 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.

如果未 null``comparer,則會使用指定的 IComparer 執行,將 array 的元素與指定的值進行比較。If 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.

如果 null``comparer,則會使用元素本身或指定值所提供的 IComparable 執行來進行比較。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,而 value 未執行 IComparable 介面,則在開始搜尋之前,不會針對 array 測試 IComparable 的元素。If 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的專案,則會擲回例外狀況(exception)。An exception is thrown if the search encounters an element that does not implement IComparable.

允許重複的元素。Duplicate elements are allowed. 如果 Array 包含多個等於 value的元素,此方法只會傳回其中一個出現專案的索引,而不一定是第一個發生的。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.

null 一律可以與任何其他參考型別進行比較;因此,與 null 的比較不會產生例外狀況。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception.

注意

針對每個測試的專案,value 都會傳遞至適當的 IComparable 實作為,即使 value nullFor 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 (log n)運算,其中 narrayLengthThis method is an O(log n) operation, where n is the Length of array.

另請參閱

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

要搜尋之已排序的一維 ArrayThe sorted one-dimensional Array to search.

index
Int32

要搜尋範圍的起始索引。The starting index of the range to search.

length
Int32

搜尋範圍的長度。The length of the range to search.

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

例外狀況

arraynullarray is null.

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. 在呼叫這個方法之前,必須先排序 arrayarray must be sorted before calling this method.

如果 Array 不包含指定的值,則此方法會傳回負整數。If the Array does not contain the specified value, the method returns a negative integer. 您可以將位補數運算子(~ in 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.

valuearray 的每個元素都必須執行 IComparable 介面,以用於比較。Either 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.

注意

如果 value 不會執行 IComparable 介面,則在開始搜尋之前,不會針對 IComparable 測試 array 的元素。If value does not implement the IComparable interface, the elements of array are not tested for IComparable before the search begins. 如果搜尋遇到不會執行 IComparable的專案,則會擲回例外狀況(exception)。An exception is thrown if the search encounters an element that does not implement IComparable.

允許重複的元素。Duplicate elements are allowed. 如果 Array 包含多個等於 value的元素,此方法只會傳回其中一個出現專案的索引,而不一定是第一個發生的。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.

null 一律可以與任何其他參考型別進行比較;因此,與 null 的比較不會產生例外狀況。null can always be compared with any other reference type; therefore, comparisons with null do not generate an exception.

注意

針對每個測試的專案,value 都會傳遞至適當的 IComparable 實作為,即使 value nullFor 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 (log n)作業,其中 nlengthThis method is an O(log n) operation, where n is length.

另請參閱

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

要搜尋之已排序的一維 ArrayThe sorted one-dimensional Array to search.

index
Int32

要搜尋範圍的起始索引。The starting index of the range to search.

length
Int32

搜尋範圍的長度。The length of the range to search.

value
Object

要搜尋的物件。The object to search for.

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

例外狀況

arraynullarray is null.

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. 在呼叫這個方法之前,必須先排序 arrayarray must be sorted before calling this method.

如果 Array 不包含指定的值,則此方法會傳回負整數。If the Array does not contain the specified value, the method returns a negative integer. 您可以將位補數運算子(~ in 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.

如果未 null``comparer,則會使用指定的 IComparer 執行,將 array 的元素與指定的值進行比較。If 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.

如果 null``comparer,則會使用元素本身或指定值所提供的 IComparable 執行來進行比較。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,而 value 未執行 IComparable 介面,則在開始搜尋之前,不會針對 array 測試 IComparable 的元素。If 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的專案,則會擲回例外狀況(exception)。An exception is thrown if the search encounters an element that does not implement IComparable.

允許重複的元素。Duplicate elements are allowed. 如果 Array 包含多個等於 value的元素,此方法只會傳回其中一個出現專案的索引,而不一定是第一個發生的。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.

null 一律可以與任何其他參考型別進行比較;因此,使用 IComparable時,與 null 的比較並不會產生例外狀況。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 nullFor 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 (log n)作業,其中 nlengthThis method is an O(log n) operation, where n is length.

另請參閱

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[]

要搜尋的一維 Array (其以零為起始且已排序)。The sorted one-dimensional, zero-based Array to search.

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

例外狀況

arraynullarray is null.

T 不實作 IComparable<T> 泛型介面。T does not implement the IComparable<T> generic interface.

範例

下列程式碼範例示範 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.

注意

SortBinarySearch 泛型方法的呼叫並不會與其非泛型對應項的呼叫外觀不同,因為 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#和 Visual C++中為 ~ 運算子,在 Visual Basic 中則為 Xor-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.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. 在呼叫這個方法之前,必須先排序 arrayarray must be sorted before calling this method.

如果 array 不包含指定的值,則此方法會傳回負整數。If array does not contain the specified value, the method returns a negative integer. 您可以將位補數運算子(~ in 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. 如果 Array 包含多個等於 value的元素,此方法只會傳回其中一個出現專案的索引,而不一定是第一個發生的。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.

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 nullFor 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 (log n)運算,其中 narrayLengthThis method is an O(log n) operation, where n is the Length of array.

另請參閱

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[]

要搜尋的一維 Array (其以零為起始且已排序)。The sorted one-dimensional, zero-based Array to search.

value
T

要搜尋的物件。The object to search for.

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

例外狀況

arraynullarray is null.

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>IComparer(Of String) 在 Visual Basic C++中,在 Visual 中為 IComparer<String^>)泛型介面。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#和 Visual C++中的 ~ 運算子,在 Visual Basic 中則為 Xor-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.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. 在呼叫這個方法之前,必須先排序 arrayarray must be sorted before calling this method.

如果 Array 不包含指定的值,則此方法會傳回負整數。If the Array does not contain the specified value, the method returns a negative integer. 您可以將位補數運算子(~ in 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.

如果未 null``comparer,則會使用指定的 IComparer<T> 泛型介面執行,將 array 的元素與指定的值進行比較。If 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.

如果 null``comparer,則會使用 T所提供的 IComparable<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,而 value 未執行 IComparable<T> 泛型介面,則在開始搜尋之前,不會針對 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>的專案,則會擲回例外狀況(exception)。An exception is thrown if the search encounters an element that does not implement IComparable<T>.

允許重複的元素。Duplicate elements are allowed. 如果 Array 包含多個等於 value的元素,此方法只會傳回其中一個出現專案的索引,而不一定是第一個發生的。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.

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 nullFor 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 (log n)運算,其中 narrayLengthThis method is an O(log n) operation, where n is the Length of array.

另請參閱

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

要搜尋範圍的起始索引。The starting index of the range to search.

length
Int32

搜尋範圍的長度。The length of the range to search.

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

例外狀況

arraynullarray is null.

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.

T 不實作 IComparable<T> 泛型介面。T does not implement the IComparable<T> generic interface.

備註

這個方法不支援搜尋包含負索引的陣列。This method does not support searching arrays that contain negative indexes. 在呼叫這個方法之前,必須先排序 arrayarray must be sorted before calling this method.

如果陣列不包含指定的值,則方法會傳回負整數。If the array does not contain the specified value, the method returns a negative integer. 您可以將位補數運算子(~ in 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. 如果 Array 包含多個等於 value的元素,此方法只會傳回其中一個出現專案的索引,而不一定是第一個發生的。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.

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 nullFor 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 (log n)作業,其中 nlengthThis method is an O(log n) operation, where n is length.

另請參閱

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

要搜尋範圍的起始索引。The starting index of the range to search.

length
Int32

搜尋範圍的長度。The length of the range to search.

value
T

要搜尋的物件。The object to search for.

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

例外狀況

arraynullarray is null.

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. 在呼叫這個方法之前,必須先排序 arrayarray must be sorted before calling this method.

如果陣列不包含指定的值,則方法會傳回負整數。If the array does not contain the specified value, the method returns a negative integer. 您可以將位補數運算子(~ in 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.

如果未 null``comparer,則會使用指定的 IComparer<T> 泛型介面執行,將 array 的元素與指定的值進行比較。If 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.

如果 null``comparer,則會使用針對類型 T提供的 IComparable<T> 泛型介面執行來進行比較。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. 如果 Array 包含多個等於 value的元素,此方法只會傳回其中一個出現專案的索引,而不一定是第一個發生的。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.

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 nullFor 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 (log n)作業,其中 nlengthThis method is an O(log n) operation, where n is length.

另請參閱

適用於