Array.BinarySearch 方法

定義

使用二進位搜尋演算法,在一維且已排序的 Array 中搜尋值。

多載

BinarySearch(Array, Object)

使用陣列每個項目和指定物件所實作的 IComparable 介面,在整個一維已排序的陣列中搜尋特定的項目。

BinarySearch(Array, Object, IComparer)

使用指定的 IComparer 介面,在整個一維已排序的陣列中搜尋值。

BinarySearch(Array, Int32, Int32, Object)

使用陣列的每個項目和指定之值所實作的 IComparable 介面,在已排序的一維陣列內某個範圍的項目中搜尋值。

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

使用指定的 IComparer 介面,在已排序的一維陣列內某範圍的項目中搜尋值。

BinarySearch<T>(T[], T)

使用 Array 的每個項目和指定之物件所實作的 IComparable<T> 泛型介面,在整個已排序的一維陣列中搜尋特定的項目。

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

使用指定的 IComparer<T> 泛型介面,在整個已排序的一維陣列中搜尋值。

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

使用 Array 的每個項目和指定值所實作的 IComparable<T> 泛型介面,在一維已排序的陣列內某個範圍的項目中搜尋值。

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

使用指定的 IComparer<T> 泛型介面,在已排序的一維陣列內某範圍的項目中搜尋值。

BinarySearch(Array, Object)

來源:
Array.cs
來源:
Array.cs
來源:
Array.cs

使用陣列每個項目和指定物件所實作的 IComparable 介面,在整個一維已排序的陣列中搜尋特定的項目。

public:
 static int BinarySearch(Array ^ array, System::Object ^ value);
public static int BinarySearch (Array array, object value);
public static int BinarySearch (Array array, object? value);
static member BinarySearch : Array * obj -> int
Public Shared Function BinarySearch (array As Array, value As Object) As Integer

參數

array
Array

要搜尋的已排序之一維 Array

value
Object

要搜尋的物件。

傳回

如果找到 value,則為指定的 array 中指定的 value 索引;否則為負數。 如果找不到 valuevalue 小於 array 的一或多個項目,傳回的負數是大於 value 的第一個項目索引的位元補數。 如果找不到 valuevalue 大於 array 的所有項目,傳回的負數是 (最後一個項目索引加 1) 的位元補數。 如果以未排序的 array 來呼叫這個方法,傳回值會不正確且可能傳回負數,即使 value 出現在 array 中也一樣。

例外狀況

arraynull

array 是多維的。

value 的類型與 array 項目不相容。

value 不會實作 IComparable 介面,且搜尋時遇到未實作 IComparable 介面的項目。

範例

下列程式碼範例示範如何使用 BinarySearch 在 中 Array 尋找特定物件。

注意

陣列是以遞增排序次序建立的元素。 方法 BinarySearch 需要以遞增順序排序陣列。

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.
open System

let printValues (myArray: Array) =
    let mutable i = 0
    let cols = myArray.GetLength(myArray.Rank - 1)
    for item in myArray do
        if i < cols then
            i <- i + 1
        else
            printfn ""
            i <- 1;
        printf $"\t{item}"
    printfn ""

let findMyObject (myArr: Array) (myObject: obj) =
    let myIndex = Array.BinarySearch(myArr, myObject)
    if myIndex < 0 then
        printfn $"The object to search for ({myObject}) is not found. The next larger object is at index {~~~myIndex}."
    else
        printfn $"The object to search for ({myObject}) is at index {myIndex}."

// Creates and initializes a new Array.
let myIntArray = [| 8; 2; 6; 3; 7 |]

// Do the required sort first
Array.Sort myIntArray

// Displays the values of the Array.
printfn "The int array contains the following:"
printValues myIntArray

// Locates a specific object that does not exist in the Array.
let myObjectOdd: obj = 1
findMyObject myIntArray myObjectOdd 

// Locates an object that exists in the Array.
let myObjectEven: obj = 6
findMyObject myIntArray myObjectEven
       
// This code produces the following output:
//     The int 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(int), 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 int 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 int 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.

備註

這個方法不支援搜尋包含負索引的陣列。 array 必須先排序,才能呼叫這個方法。

Array如果 不包含指定的值,則方法會傳回負整數。 您可以在 C# 中套用位補數運算子 (~ , Not 在 Visual Basic) 套用至負結果,以產生索引。 如果這個索引是大於陣列的上限,則陣列中沒有大於 value 的專案。 否則,它是大於 value 的第一個專案索引。

value的 或 每個元素 array 都必須實 IComparable 作 介面,以便進行比較。 的元素 array 必須已根據實作所 IComparable 定義的排序次序,以遞增值排序;否則結果可能不正確。

注意

如果未 value 實作 IComparable 介面,搜尋開始之前不會測試 IComparablearray 元素。 如果搜尋遇到未實 IComparable 作 的專案,則會擲回例外狀況。

允許重複的專案。 Array如果 包含一個以上的元素等於 value ,則 方法只會傳回其中一個出現的索引,不一定傳回第一個專案的索引。

null 一律可以與任何其他參考類型進行比較;因此,與 null 的比較不會產生例外狀況。

注意

針對測試的每個專案, value 即使 是 null ,也會 value 傳遞至適當的 IComparable 實作。 也就是說,實作 IComparable 會決定給定專案與 的比較 null 方式。

這個方法是 O (記錄 n) 作業,其中 nLengtharray

另請參閱

適用於

BinarySearch(Array, Object, IComparer)

來源:
Array.cs
來源:
Array.cs
來源:
Array.cs

使用指定的 IComparer 介面,在整個一維已排序的陣列中搜尋值。

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);
public static int BinarySearch (Array array, object? value, System.Collections.IComparer? comparer);
static member BinarySearch : Array * obj * System.Collections.IComparer -> int
Public Shared Function BinarySearch (array As Array, value As Object, comparer As IComparer) As Integer

參數

array
Array

要搜尋的已排序之一維 Array

value
Object

要搜尋的物件。

comparer
IComparer

比較項目時所要使用的 IComparer 實作。

-或-

null 表示會使用每個項目的 IComparable 實作。

傳回

如果找到 value,則為指定的 array 中指定的 value 索引;否則為負數。 如果找不到 valuevalue 小於 array 的一或多個項目,傳回的負數是大於 value 的第一個項目索引的位元補數。 如果找不到 valuevalue 大於 array 的所有項目,傳回的負數是 (最後一個項目索引加 1) 的位元補數。 如果以未排序的 array 來呼叫這個方法,傳回值會不正確且可能傳回負數,即使 value 出現在 array 中也一樣。

例外狀況

arraynull

array 是多維的。

comparernull,且 value 的類型與 array 項目不相容。

comparernullvalue 不會實作 IComparable 介面,且搜尋時遇到未實作 IComparable 介面的項目。

備註

這個方法不支援搜尋包含負索引的陣列。 array 必須先排序,才能呼叫這個方法。

Array如果 不包含指定的值,則方法會傳回負整數。 您可以在 C# 中套用位補數運算子 (~ , Not 在 Visual Basic) 套用至負結果,以產生索引。 如果這個索引是大於陣列的上限,則陣列中沒有大於 value 的專案。 否則,它是大於 value 的第一個專案索引。

比較子會自訂元素的比較方式。 例如,您可以使用 System.Collections.CaseInsensitiveComparer 做為比較子來執行不區分大小寫的字串搜尋。

如果 comparer 不是 null ,則會使用指定的實作,將 的 array 元素與指定的 IComparer 值進行比較。 的元素 array 必須已根據 所 comparer 定義的排序次序,以遞增值排序;否則結果可能不正確。

如果 為 comparernull ,則比較是使用 IComparable 專案本身或指定值所提供的實作來完成。 的元素 array 必須已根據實作所 IComparable 定義的排序次序,以遞增值排序;否則結果可能不正確。

注意

如果 comparernullvalue 未實 IComparable 作 介面,則 的元素 array 不會在搜尋開始之前進行測試 IComparable 。 如果搜尋遇到未實 IComparable 作 的專案,則會擲回例外狀況。

允許重複的專案。 Array如果 包含一個以上的元素等於 value ,則 方法只會傳回其中一個出現的索引,不一定傳回第一個專案的索引。

null 一律可以與任何其他參考類型進行比較;因此,與 null 的比較不會產生例外狀況。

注意

針對測試的每個專案, value 即使 是 null ,也會 value 傳遞至適當的 IComparable 實作。 也就是說,實作 IComparable 會決定給定專案與 的比較 null 方式。

這個方法是 O (記錄 n) 作業,其中 nLengtharray

另請參閱

適用於

BinarySearch(Array, Int32, Int32, Object)

來源:
Array.cs
來源:
Array.cs
來源:
Array.cs

使用陣列的每個項目和指定之值所實作的 IComparable 介面,在已排序的一維陣列內某個範圍的項目中搜尋值。

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);
public static int BinarySearch (Array array, int index, int length, object? value);
static member BinarySearch : Array * int * int * obj -> int
Public Shared Function BinarySearch (array As Array, index As Integer, length As Integer, value As Object) As Integer

參數

array
Array

要搜尋的已排序之一維 Array

index
Int32

要搜尋範圍的起始索引。

length
Int32

搜尋範圍的長度。

value
Object

要搜尋的物件。

傳回

如果找到 value,則為指定的 array 中指定的 value 索引;否則為負數。 如果找不到 valuevalue 小於 array 的一或多個項目,傳回的負數是大於 value 的第一個項目索引的位元補數。 如果找不到 valuevalue 大於 array 的所有項目,傳回的負數是 (最後一個項目索引加 1) 的位元補數。 如果以未排序的 array 來呼叫這個方法,傳回值會不正確且可能傳回負數,即使 value 出現在 array 中也一樣。

例外狀況

arraynull

array 是多維的。

index 小於 array 的下限。

-或-

length 小於零。

indexlength 未指定 array 中的有效範圍。

-或-

value 的類型與 array 項目不相容。

value 不會實作 IComparable 介面,且搜尋時遇到未實作 IComparable 介面的項目。

備註

這個方法不支援搜尋包含負索引的陣列。 array 必須先排序,才能呼叫這個方法。

Array如果 不包含指定的值,則方法會傳回負整數。 您可以在 C# 中套用位補數運算子 (~ , Not 在 Visual Basic) 套用至負結果,以產生索引。 如果這個索引是大於陣列的上限,則陣列中沒有大於 value 的專案。 否則,它是大於 value 的第一個專案索引。

value的 或 每個元素 array 都必須實 IComparable 作 介面,以便進行比較。 的元素 array 必須已根據實作所 IComparable 定義的排序次序,以遞增值排序;否則結果可能不正確。

注意

如果未 value 實作 IComparable 介面,搜尋開始之前不會測試 IComparablearray 元素。 如果搜尋遇到未實 IComparable 作 的專案,則會擲回例外狀況。

允許重複的專案。 Array如果 包含一個以上的元素等於 value ,則 方法只會傳回其中一個出現的索引,不一定傳回第一個專案的索引。

null 一律可以與任何其他參考類型進行比較;因此,與 null 的比較不會產生例外狀況。

注意

針對測試的每個專案, value 即使 是 null ,也會 value 傳遞至適當的 IComparable 實作。 也就是說,實作 IComparable 會決定給定專案與 的比較 null 方式。

這個方法是 O (記錄 n) 作業,其中 nlength

另請參閱

適用於

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

來源:
Array.cs
來源:
Array.cs
來源:
Array.cs

使用指定的 IComparer 介面,在已排序的一維陣列內某範圍的項目中搜尋值。

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);
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
Public Shared Function BinarySearch (array As Array, index As Integer, length As Integer, value As Object, comparer As IComparer) As Integer

參數

array
Array

要搜尋的已排序之一維 Array

index
Int32

要搜尋範圍的起始索引。

length
Int32

搜尋範圍的長度。

value
Object

要搜尋的物件。

comparer
IComparer

比較項目時所要使用的 IComparer 實作。

-或-

null 表示會使用每個項目的 IComparable 實作。

傳回

如果找到 value,則為指定的 array 中指定的 value 索引;否則為負數。 如果找不到 valuevalue 小於 array 的一或多個項目,傳回的負數是大於 value 的第一個項目索引的位元補數。 如果找不到 valuevalue 大於 array 的所有項目,傳回的負數是 (最後一個項目索引加 1) 的位元補數。 如果以未排序的 array 來呼叫這個方法,傳回值會不正確且可能傳回負數,即使 value 出現在 array 中也一樣。

例外狀況

arraynull

array 是多維的。

index 小於 array 的下限。

-或-

length 小於零。

indexlength 未指定 array 中的有效範圍。

-或-

comparernull,且 value 的類型與 array 項目不相容。

comparernullvalue 不會實作 IComparable 介面,且搜尋時遇到未實作 IComparable 介面的項目。

備註

這個方法不支援搜尋包含負索引的陣列。 array 必須先排序,才能呼叫這個方法。

Array如果 不包含指定的值,則方法會傳回負整數。 您可以在 C# 中套用位補數運算子 (~ , Not 在 Visual Basic) 套用至負結果,以產生索引。 如果這個索引是大於陣列的上限,則陣列中沒有大於 value 的專案。 否則,它是大於 value 的第一個專案索引。

比較子會自訂元素的比較方式。 例如,您可以使用 System.Collections.CaseInsensitiveComparer 做為比較子來執行不區分大小寫的字串搜尋。

如果 comparer 不是 null ,則會使用指定的實作,將 的 array 元素與指定的 IComparer 值進行比較。 的元素 array 必須已根據 所 comparer 定義的排序次序,以遞增值排序;否則結果可能不正確。

如果 為 comparernull ,則比較是使用 IComparable 專案本身或指定值所提供的實作來完成。 的元素 array 必須已根據實作所 IComparable 定義的排序次序,以遞增值排序;否則結果可能不正確。

注意

如果 comparernullvalue 未實 IComparable 作 介面,則 的元素 array 不會在搜尋開始之前進行測試 IComparable 。 如果搜尋遇到未實 IComparable 作 的專案,則會擲回例外狀況。

允許重複的專案。 Array如果 包含一個以上的元素等於 value ,則 方法只會傳回其中一個出現的索引,不一定傳回第一個專案的索引。

null一律可以與任何其他參考類型進行比較;因此,使用 IComparable 時,與 null 的比較不會產生例外狀況。

注意

針對測試的每個專案, value 即使 是 null ,也會 value 傳遞至適當的 IComparable 實作。 也就是說,實作 IComparable 會決定給定專案與 的比較 null 方式。

這個方法是 O (記錄 n) 作業,其中 nlength

另請參閱

適用於

BinarySearch<T>(T[], T)

來源:
Array.cs
來源:
Array.cs
來源:
Array.cs

使用 Array 的每個項目和指定之物件所實作的 IComparable<T> 泛型介面,在整個已排序的一維陣列中搜尋特定的項目。

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

陣列項目的類型。

參數

array
T[]

要搜尋的已排序且為一維之以零為起始的 Array

value
T

要搜尋的物件。

傳回

如果找到 value,則為指定的 array 中指定的 value 索引;否則為負數。 如果找不到 valuevalue 小於 array 的一或多個項目,傳回的負數是大於 value 的第一個項目索引的位元補數。 如果找不到 valuevalue 大於 array 的所有項目,傳回的負數是 (最後一個項目索引加 1) 的位元補數。 如果以未排序的 array 來呼叫這個方法,傳回值會不正確且可能傳回負數,即使 value 出現在 array 中也一樣。

例外狀況

arraynull

T 不實作 IComparable<T> 泛型介面。

範例

下列程式碼範例示範 Sort<T>(T[]) 泛型方法多載和 BinarySearch<T>(T[], T) 泛型方法多載。 建立字串陣列,不依特定順序。

陣列會再次顯示、排序及顯示。 陣列必須經過排序,才能使用 BinarySearch 方法。

注意

對 和 BinarySearch 泛型方法的呼叫不會與其非一般對應專案的呼叫 Sort 不同,因為 Visual Basic、F#、C# 和 C++ 會從第一個引數的類型推斷泛型型別參數的類型。 如果您使用Ildasm.exe (IL 反組譯程式) 來檢查Microsoft中繼語言 (MSIL) ,您可以看到正在呼叫泛型方法。

BinarySearch<T>(T[], T)然後,泛型方法多載會用來搜尋兩個字串,一個不在陣列中,另一個則為 。 陣列和 方法的 BinarySearch 傳回值會傳遞至 ShowWhere 泛型方法, showWhere (F# 範例中的函式) ,如果找到字串,則會顯示索引值,否則搜尋字串在陣列中時會落在其中的專案。 如果字串不在陣列中,則索引為負數,因此 ShowWhere 方法會採用位補數 (C# 和 Visual C++ 中的 ~ 運算子, Xor 在 Visual) Basic 中為 - 1 的 - 1 ,以取得大於搜尋字串之清單中第一個專案的索引。

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.
 */
open System

let showWhere (array: 'a []) index =
    if index < 0 then
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        let index = ~~~index

        printf "Not found. Sorts between: "

        if index = 0 then
            printf "beginning of array and "
        else
            printf $"{array[index - 1]} and "

        if index = array.Length then
            printfn "end of array."
        else
            printfn $"{array[index]}."
    else
        printfn $"Found at index {index}."

let dinosaurs =
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Tyrannosaurus"
       "Mamenchisaurus"
       "Deinonychus"
       "Edmontosaurus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nSort"
Array.Sort dinosaurs

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nBinarySearch for 'Coelophysis':"
let index = Array.BinarySearch(dinosaurs, "Coelophysis")
showWhere dinosaurs index

printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus")
|> showWhere dinosaurs


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

備註

這個方法不支援搜尋包含負索引的陣列。 array 必須先排序,才能呼叫這個方法。

如果 array 不包含指定的值,則方法會傳回負整數。 您可以在 C# 中套用位補數運算子 (~ , Not 在 Visual Basic) 套用至負結果,以產生索引。 如果這個索引等於陣列的大小,則陣列中沒有大於 value 的專案。 否則,它是大於 value 的第一個專案索引。

T 必須實作 IComparable<T> 用於比較的泛型介面。 的元素 array 必須已根據實作所 IComparable<T> 定義的排序次序,以遞增值排序;否則結果可能不正確。

允許重複的專案。 Array如果 包含一個以上的元素等於 value ,則 方法只會傳回其中一個出現的索引,不一定傳回第一個專案的索引。

null 一律可以與任何其他參考類型進行比較;因此,與 null 的比較不會產生例外狀況。

注意

針對測試的每個專案, value 即使 是 null ,也會 value 傳遞至適當的 IComparable<T> 實作。 也就是說,實作 IComparable<T> 會決定給定專案與 的比較 null 方式。

這個方法是 O (記錄 n) 作業,其中 nLengtharray

另請參閱

適用於

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

來源:
Array.cs
來源:
Array.cs
來源:
Array.cs

使用指定的 IComparer<T> 泛型介面,在整個已排序的一維陣列中搜尋值。

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

陣列項目的類型。

參數

array
T[]

要搜尋的已排序且為一維之以零為起始的 Array

value
T

要搜尋的物件。

comparer
IComparer<T>

比較項目時所要使用的 IComparer<T> 實作。

-或-

null 表示會使用每個項目的 IComparable<T> 實作。

傳回

如果找到 value,則為指定的 array 中指定的 value 索引;否則為負數。 如果找不到 valuevalue 小於 array 的一或多個項目,傳回的負數是大於 value 的第一個項目索引的位元補數。 如果找不到 valuevalue 大於 array 的所有項目,傳回的負數是 (最後一個項目索引加 1) 的位元補數。 如果以未排序的 array 來呼叫這個方法,傳回值會不正確且可能傳回負數,即使 value 出現在 array 中也一樣。

例外狀況

arraynull

comparernull,且 value 的類型與 array 項目不相容。

comparernull,且 T 未實作 IComparable<T> 泛型介面

範例

下列範例示範 Sort<T>(T[], IComparer<T>) 泛型方法多載和 BinarySearch<T>(T[], T, IComparer<T>) 泛型方法多載。

程式碼範例會針對名為 ReverseCompare 的字串定義替代比較子,它會 IComparer<string> 在 Visual Basic 中實作 Visual Basic 中的 (IComparer(Of String)IComparer<String^>) 泛型介面。 比較子會呼叫 CompareTo(String) 方法,反轉比較子的順序,讓字串排序高到低,而不是低到高。

陣列隨即顯示、排序,並再次顯示。 陣列必須經過排序,才能使用 BinarySearch 方法。

注意

對 和 BinarySearch<T>(T[], T, IComparer<T>) 泛型方法的呼叫 Sort<T>(T[], IComparer<T>) 看起來與對非泛型方法的呼叫不同,因為 Visual Basic、C# 和 C++ 會從第一個引數的類型推斷泛型型別參數的類型。 如果您使用Ildasm.exe (IL 反組譯程式) 來檢查Microsoft中繼語言 (MSIL) ,您可以看到正在呼叫泛型方法。

接著會 BinarySearch<T>(T[], T, IComparer<T>) 使用泛型方法多載來搜尋兩個字串,一個不在陣列中,另一個則為 。 方法的 BinarySearch<T>(T[], T, IComparer<T>) 陣列和傳回值會傳遞至 ShowWhere 泛型方法, showWhere (F# 範例中的 函式) ,如果找到字串,則會顯示索引值,否則搜尋字串在陣列中時會落在兩者之間的專案。 如果字串不是 n 陣列,則 ShowWhere 索引為負數,因此方法會採用位補數 (C# 和 Visual C++ 中的 ~ 運算子,而 Visual) Basic 中為 - 1 中的 運算子, Xor 以取得清單中大於搜尋字串之第一個專案的索引。

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.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            // Compare y and x in reverse order.
            y.CompareTo x

let showWhere (array: 'a []) index =
    if index < 0 then
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        let index = ~~~index

        printf "Not found. Sorts between: "

        if index = 0 then
            printf "beginning of array and "
        else
            printf $"{array[index - 1]} and "

        if index = array.Length then
            printfn "end of array."
        else
            printfn $"{array[index]}."
    else
        printfn $"Found at index {index}."

let dinosaurs =
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Tyrannosaurus"
       "Mamenchisaurus"
       "Deinonychus"
       "Edmontosaurus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

let rc = ReverseComparer()

printfn "\nSort"
Array.Sort(dinosaurs, rc)

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nBinarySearch for 'Coelophysis':"
Array.BinarySearch(dinosaurs, "Coelophysis", rc)
|> showWhere dinosaurs

printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
|> showWhere dinosaurs


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

備註

這個方法不支援搜尋包含負索引的陣列。 array 必須在呼叫這個方法之前排序。

Array如果 不包含指定的值,方法會傳回負整數。 您可以在 C# 中將位補數運算子 (~ 套用至負數結果) , Not 以產生索引。 如果此索引等於陣列的大小,則陣列中沒有大於 value 的專案。 否則,它是大於 value 的第一個專案索引。

比較子會自訂專案比較方式。 例如,您可以使用 System.Collections.CaseInsensitiveComparer 做為比較子來執行不區分大小寫的字串搜尋。

如果 comparer 不是 null ,則會使用指定的泛型介面實作,將 的 array 元素與指定的 IComparer<T> 值進行比較。 的專案 array 必須已經根據 所 comparer 定義的排序次序,以遞增值排序;否則結果可能不正確。

如果 comparernull ,則會使用 IComparable<T> 所提供的 T 泛型介面實作來完成比較。 array的專案必須已根據實作所 IComparable<T> 定義的排序次序,以遞增值排序;否則結果可能不正確。

注意

如果 為 comparernullvalue 未實作 IComparable<T> 泛型介面,則 的元素 array 不會在搜尋開始之前進行測試 IComparable<T> 。 如果搜尋遇到未實 IComparable<T> 作 的專案,就會擲回例外狀況。

允許重複的專案。 Array如果 包含一個以上的元素等於 value ,則 方法只會傳回其中一個出現的索引,不一定傳回第一個專案的索引。

null 一律可以與任何其他參考型別進行比較;因此,與 null 的比較不會產生例外狀況。

注意

針對測試的每個元素, value 即使 valuenull ,也會傳遞至適當的 IComparable<T> 實作。 也就是說,實作 IComparable<T> 會決定給定專案與 的比較 null 方式。

這個方法是 O (記錄 n) 作業,其中 nLengtharray

另請參閱

適用於

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

來源:
Array.cs
來源:
Array.cs
來源:
Array.cs

使用 Array 的每個項目和指定值所實作的 IComparable<T> 泛型介面,在一維已排序的陣列內某個範圍的項目中搜尋值。

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

陣列項目的類型。

參數

array
T[]

要搜尋的已排序且為一維之以零為起始的 Array

index
Int32

要搜尋範圍的起始索引。

length
Int32

搜尋範圍的長度。

value
T

要搜尋的物件。

傳回

如果找到 value,則為指定的 array 中指定的 value 索引;否則為負數。 如果找不到 valuevalue 小於 array 的一或多個項目,傳回的負數是大於 value 的第一個項目索引的位元補數。 如果找不到 valuevalue 大於 array 的所有項目,傳回的負數是 (最後一個項目索引加 1) 的位元補數。 如果以未排序的 array 來呼叫這個方法,傳回值會不正確且可能傳回負數,即使 value 出現在 array 中也一樣。

例外狀況

arraynull

index 小於 array 的下限。

-或-

length 小於零。

indexlength 未指定 array 中的有效範圍。

-或-

value 的類型與 array 項目不相容。

T 不實作 IComparable<T> 泛型介面。

備註

這個方法不支援搜尋包含負索引的陣列。 array 必須在呼叫這個方法之前排序。

如果陣列不包含指定的值,此方法會傳回負整數。 您可以在 C# 中將位補數運算子 (~ 套用至負數結果) , Not 以產生索引。 如果此索引等於陣列的大小,則陣列中沒有大於 value 的專案。 否則,它是大於 value 的第一個專案索引。

T 必須實作用於比較的 IComparable<T> 泛型介面。 array的專案必須已根據實作所 IComparable<T> 定義的排序次序,以遞增值排序;否則結果可能不正確。

允許重複的專案。 Array如果 包含一個以上的元素等於 value ,則 方法只會傳回其中一個出現的索引,不一定傳回第一個專案的索引。

null 一律可以與任何其他參考型別進行比較;因此,與 null 的比較不會產生例外狀況。

注意

針對測試的每個元素, value 即使 valuenull ,也會傳遞至適當的 IComparable<T> 實作。 也就是說,實作 IComparable<T> 會決定給定專案與 的比較 null 方式。

這個方法是 O (記錄 n) 作業,其中 nlength

另請參閱

適用於

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

來源:
Array.cs
來源:
Array.cs
來源:
Array.cs

使用指定的 IComparer<T> 泛型介面,在已排序的一維陣列內某範圍的項目中搜尋值。

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

陣列項目的類型。

參數

array
T[]

要搜尋的已排序且為一維之以零為起始的 Array

index
Int32

要搜尋範圍的起始索引。

length
Int32

搜尋範圍的長度。

value
T

要搜尋的物件。

comparer
IComparer<T>

比較項目時所要使用的 IComparer<T> 實作。

-或-

null 表示會使用每個項目的 IComparable<T> 實作。

傳回

如果找到 value,則為指定的 array 中指定的 value 索引;否則為負數。 如果找不到 valuevalue 小於 array 的一或多個項目,傳回的負數是大於 value 的第一個項目索引的位元補數。 如果找不到 valuevalue 大於 array 的所有項目,傳回的負數是 (最後一個項目索引加 1) 的位元補數。 如果以未排序的 array 來呼叫這個方法,傳回值會不正確且可能傳回負數,即使 value 出現在 array 中也一樣。

例外狀況

arraynull

index 小於 array 的下限。

-或-

length 小於零。

indexlength 未指定 array 中的有效範圍。

-或-

comparernull,且 value 的類型與 array 項目不相容。

comparernull,且 T 未實作 IComparable<T> 泛型介面。

備註

這個方法不支援搜尋包含負索引的陣列。 array 必須在呼叫這個方法之前排序。

如果陣列不包含指定的值,此方法會傳回負整數。 您可以在 C# 中將位補數運算子 (~ 套用至負數結果) , Not 以產生索引。 如果此索引等於陣列的大小,則陣列中沒有大於 value 的專案。 否則,它是大於 value 的第一個專案索引。

比較子會自訂專案比較方式。 例如,您可以使用 System.Collections.CaseInsensitiveComparer 做為比較子來執行不區分大小寫的字串搜尋。

如果 comparer 不是 null ,則會使用指定的泛型介面實作,將 的 array 元素與指定的 IComparer<T> 值進行比較。 的專案 array 必須已經根據 所 comparer 定義的排序次序,以遞增值排序;否則結果可能不正確。

如果 comparernull ,則會使用 IComparable<T> 提供給 類型的 T 泛型介面實作來完成比較。 array的專案必須已根據實作所 IComparable<T> 定義的排序次序,以遞增值排序;否則結果可能不正確。

允許重複的專案。 Array如果 包含一個以上的元素等於 value ,則 方法只會傳回其中一個出現的索引,不一定傳回第一個專案的索引。

null一律可以與任何其他參考型別進行比較;因此,使用 IComparable<T> 時,與 null 的比較不會產生例外狀況。

注意

針對測試的每個元素, value 即使 valuenull ,也會傳遞至適當的 IComparable<T> 實作。 也就是說,實作 IComparable<T> 會決定給定專案與 的比較 null 方式。

這個方法是 O (記錄 n) 作業,其中 nlength

另請參閱

適用於