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找不到特定的物件中ArrayThe 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. 否則,即大於第一個項目的索引valueOtherwise, it is the index of the first element that is larger than value.

value或 每個項目array必須實作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介面的項目array並未經過測試的IComparable搜尋開始之前。Ifvalue does not implement the IComparable interface, the elements of array are not tested for IComparable before the search begins. 如果搜尋遇到不實作的項目,會擲回例外狀況IComparableAn 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實作,即使valuenullFor every element tested, value is passed to the appropriate IComparable implementation, even if value is null. 亦即IComparable實作會判定指定的項目来比較的方式nullThat is, the IComparable implementation determines how a given element compares to null.

這個方法是 O (log n) 運算,其中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. 否則,即大於第一個項目的索引valueOtherwise, 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.

如果comparer不是null的項目array會指定使用指定的值比較IComparer實作。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.

如果comparernull,比較完成使用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.

注意

如果comparernullvalue不會實作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. 如果搜尋遇到不實作的項目,會擲回例外狀況IComparableAn 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實作,即使valuenullFor every element tested, value is passed to the appropriate IComparable implementation, even if value is null. 亦即IComparable實作會判定指定的項目来比較的方式nullThat is, the IComparable implementation determines how a given element compares to null.

這個方法是 O (log n) 運算,其中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. 否則,即大於第一個項目的索引valueOtherwise, it is the index of the first element that is larger than value.

value或 每個項目array必須實作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介面的項目array並未經過測試的IComparable搜尋開始之前。If value does not implement the IComparable interface, the elements of array are not tested for IComparable before the search begins. 如果搜尋遇到不實作的項目,會擲回例外狀況IComparableAn 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實作,即使valuenullFor every element tested, value is passed to the appropriate IComparable implementation, even if value is null. 亦即IComparable實作會判定指定的項目来比較的方式nullThat 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) 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. 否則,即大於第一個項目的索引valueOtherwise, 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.

如果comparer不是null的項目array會指定使用指定的值比較IComparer實作。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.

如果comparernull,比較完成使用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.

注意

如果comparernullvalue不會實作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. 如果搜尋遇到不實作的項目,會擲回例外狀況IComparableAn 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不會產生例外狀況時使用IComparablenull can always be compared with any other reference type; therefore, comparisons with null do not generate an exception when using IComparable.

注意

測試每個項目的value傳遞至適當IComparable實作,即使valuenullFor every element tested, value is passed to the appropriate IComparable implementation, even if value is null. 亦即IComparable實作會判定指定的項目来比較的方式nullThat 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) 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[]

要搜尋的一維 Array (其以零為起始且已排序)。The 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.

注意

呼叫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.exe (IL 反組譯工具)若要檢查的 Microsoft intermediate language (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++, Xor-1,在 Visual Basic 中的) 取得大於清單中的第一個元素的索引比的搜尋字串。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. 否則,即大於第一個項目的索引valueOtherwise, 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>實作,即使valuenullFor every element tested, value is passed to the appropriate IComparable<T> implementation, even if value is null. 亦即IComparable<T>實作會判定指定的項目来比較的方式nullThat is, the IComparable<T> implementation determines how a given element compares to null.

這個方法是 O (log n) 運算,其中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[]

要搜尋的一維 Array (其以零為起始且已排序)。The 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>(IComparer(Of String)在 Visual BasicIComparer<String^>視覺效果中C++) 泛型介面。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.exe (IL 反組譯工具)若要檢查的 Microsoft intermediate language (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++, Xor -1,在 Visual Basic 中的) 取得的索引大於清單中的第一個元素搜尋字串。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. 否則,即大於第一個項目的索引valueOtherwise, 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.

如果comparer不是null的項目array會指定使用指定的值比較IComparer<T>泛型介面實作。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.

如果comparernull,比較是使用IComparable<T>所提供的泛型介面實作TIf 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.

注意

如果comparernullvalue不會實作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>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>實作,即使valuenullFor every element tested, value is passed to the appropriate IComparable<T> implementation, even if value is null. 亦即IComparable<T>實作會判定指定的項目来比較的方式nullThat is, the IComparable<T> implementation determines how a given element compares to null.

這個方法是 O (log n) 運算,其中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. 否則,即大於第一個項目的索引valueOtherwise, 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>實作,即使valuenullFor every element tested, value is passed to the appropriate IComparable<T> implementation, even if value is null. 亦即IComparable<T>實作會判定指定的項目来比較的方式nullThat 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>) 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. 否則,即大於第一個項目的索引valueOtherwise, 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.

如果comparer不是null的項目array會指定使用指定的值比較IComparer<T>泛型介面實作。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.

如果comparernull,比較是使用IComparable<T>類型所提供的泛型介面實作TIf 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 一定要與其他參考型別; 比較因此,比較null不會產生例外狀況時使用IComparable<T>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>實作,即使valuenullFor every element tested, value is passed to the appropriate IComparable<T> implementation, even if value is null. 亦即IComparable<T>實作會判定指定的項目来比較的方式nullThat 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.

另請參閱

適用於