Array.BinarySearch メソッド

定義

バイナリ検索アルゴリズムを使用して、1 次元の並べ替えられた Array で値を検索します。

オーバーロード

BinarySearch(Array, Object)

配列の各要素と指定したオブジェクトによって実装される IComparable インターフェイスを使用して、1 次元の並べ替えられた配列全体で特定の要素を検索します。

BinarySearch(Array, Object, IComparer)

指定した IComparer インターフェイスを使用して、1 次元の並べ替えられた配列全体で値を検索します。

BinarySearch(Array, Int32, Int32, Object)

配列の各要素と指定した値によって実装される IComparable インターフェイスを使用して、1 次元の並べ替えられた配列内の要素の範囲で値を検索します。

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

指定した IComparer インターフェイスを使用して、1 次元の並べ替えられた配列内の要素の範囲で値を検索します。

BinarySearch<T>(T[], T)

Array の各要素と指定したオブジェクトによって実装される IComparable<T> ジェネリック インターフェイスを使用して、1 次元の並べ替えられた配列全体で特定の要素を検索します。

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

指定した IComparer<T> ジェネリック インターフェイスを使用して、1 次元の並べ替えられた配列全体で値を検索します。

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

Array の各要素と指定した値によって実装される IComparable<T> ジェネリック インターフェイスを使用して、1 次元の並べ替えられた配列内の要素の範囲で値を検索します。

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

指定した IComparer<T> ジェネリック インターフェイスを使用して、1 次元の並べ替えられた配列内の要素の範囲で値を検索します。

BinarySearch(Array, Object)

ソース:
Array.cs
ソース:
Array.cs
ソース:
Array.cs

配列の各要素と指定したオブジェクトによって実装される IComparable インターフェイスを使用して、1 次元の並べ替えられた配列全体で特定の要素を検索します。

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

検索する並べ替えられた 1 次元 Array

value
Object

検索するオブジェクト。

戻り値

指定した array内の指定した value のインデックス (value が見つかった場合)。それ以外の場合は負の数。 value が見つからず、valuearray内の 1 つ以上の要素より小さい場合、返される負の数は、valueより大きい最初の要素のインデックスのビットごとの補数です。 value が見つからず、valuearray内のすべての要素より大きい場合、返される負の数はビットごとの補数 (最後の要素のインデックスに 1 を加算) です。 並べ替えされていない arrayを使用してこのメソッドを呼び出すと、戻り値が正しくなく、arrayvalue が存在する場合でも負の数が返される可能性があります。

例外

arraynullです。

array は多次元です。

value は、arrayの要素と互換性のない型です。

valueIComparable インターフェイスを実装せず、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# では ~、Visual Basic では Not) を適用してインデックスを生成できます。 このインデックスが配列の上限より 1 大きい場合、配列内に value より大きい要素はありません。 それ以外の場合は、valueより大きい最初の要素のインデックスです。

value または array のすべての要素は、比較に使用される IComparable インターフェイスを実装する必要があります。 array の要素は、IComparable 実装によって定義された並べ替え順序に従って、値を増やして既に並べ替えられている必要があります。そうしないと、結果が正しくない可能性があります。

手記

value IComparable インターフェイスが実装されていない場合、array の要素は、検索が開始される前に IComparable テストされません。 IComparableを実装していない要素が検索で検出されると、例外がスローされます。

重複する要素を使用できます。 Arrayvalueと等しい複数の要素が含まれている場合、メソッドは 1 つの出現箇所のインデックスのみを返し、必ずしも最初の要素を返すわけではありません。

null は常に他の参照型と比較できます。そのため、null との比較では例外は生成されません。

手記

テストされるすべての要素について、value は、valuenullされている場合でも、適切な IComparable 実装に渡されます。 つまり、IComparable 実装によって、特定の要素が nullと比較する方法が決まります。

このメソッドは O(ログ n) 操作です。ここで、narrayLength です。

こちらもご覧ください

  • IComparable
  • Sort
  • 配列 での Culture-Insensitive 文字列操作の実行の

適用対象

BinarySearch(Array, Object, IComparer)

ソース:
Array.cs
ソース:
Array.cs
ソース:
Array.cs

指定した IComparer インターフェイスを使用して、1 次元の並べ替えられた配列全体で値を検索します。

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

検索する並べ替えられた 1 次元 Array

value
Object

検索するオブジェクト。

comparer
IComparer

要素を比較するときに使用する IComparer 実装。

-又は-

各要素の IComparable 実装を使用 null

戻り値

指定した array内の指定した value のインデックス (value が見つかった場合)。それ以外の場合は負の数。 value が見つからず、valuearray内の 1 つ以上の要素より小さい場合、返される負の数は、valueより大きい最初の要素のインデックスのビットごとの補数です。 value が見つからず、valuearray内のすべての要素より大きい場合、返される負の数はビットごとの補数 (最後の要素のインデックスに 1 を加算) です。 並べ替えされていない arrayを使用してこのメソッドを呼び出すと、戻り値が正しくなく、arrayvalue が存在する場合でも負の数が返される可能性があります。

例外

arraynullです。

array は多次元です。

comparernullであり、valuearrayの要素と互換性のない型です。

comparer nullvalueIComparable インターフェイスを実装せず、IComparable インターフェイスを実装していない要素が検索で検出されます。

注釈

このメソッドは、負のインデックスを含む配列の検索をサポートしていません。 array は、このメソッドを呼び出す前に並べ替える必要があります。

Array に指定した値が含まれていない場合、メソッドは負の整数を返します。 負の結果にビットごとの補数演算子 (C# では ~、Visual Basic では Not) を適用してインデックスを生成できます。 このインデックスが配列の上限より 1 大きい場合、配列内に value より大きい要素はありません。 それ以外の場合は、valueより大きい最初の要素のインデックスです。

比較子は、要素の比較方法をカスタマイズします。 たとえば、比較子として System.Collections.CaseInsensitiveComparer を使用して、大文字と小文字を区別しない文字列検索を実行できます。

comparernullされていない場合、array の要素は、指定した IComparer 実装を使用して、指定した値と比較されます。 array の要素は、comparerで定義された並べ替え順序に従って、値を増やして並べ替える必要があります。そうしないと、結果が正しくない可能性があります。

comparernull場合、比較は、要素自体または指定した値によって提供される IComparable 実装を使用して行われます。 array の要素は、IComparable 実装によって定義された並べ替え順序に従って、値を増やして既に並べ替えられている必要があります。そうしないと、結果が正しくない可能性があります。

手記

comparernull され、valueIComparable インターフェイスを実装していない場合、array の要素は検索を開始する前に IComparable についてテストされません。 IComparableを実装していない要素が検索で検出されると、例外がスローされます。

重複する要素を使用できます。 Arrayvalueと等しい複数の要素が含まれている場合、メソッドは 1 つの出現箇所のインデックスのみを返し、必ずしも最初の要素を返すわけではありません。

null は常に他の参照型と比較できます。そのため、null との比較では例外は生成されません。

手記

テストされるすべての要素について、value は、valuenullされている場合でも、適切な IComparable 実装に渡されます。 つまり、IComparable 実装によって、特定の要素が nullと比較する方法が決まります。

このメソッドは O(ログ n) 操作です。ここで、narrayLength です。

こちらもご覧ください

適用対象

BinarySearch(Array, Int32, Int32, Object)

ソース:
Array.cs
ソース:
Array.cs
ソース:
Array.cs

配列の各要素と指定した値によって実装される IComparable インターフェイスを使用して、1 次元の並べ替えられた配列内の要素の範囲で値を検索します。

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

検索する並べ替えられた 1 次元 Array

index
Int32

検索する範囲の開始インデックス。

length
Int32

検索する範囲の長さ。

value
Object

検索するオブジェクト。

戻り値

指定した array内の指定した value のインデックス (value が見つかった場合)。それ以外の場合は負の数。 value が見つからず、valuearray内の 1 つ以上の要素より小さい場合、返される負の数は、valueより大きい最初の要素のインデックスのビットごとの補数です。 value が見つからず、valuearray内のすべての要素より大きい場合、返される負の数はビットごとの補数 (最後の要素のインデックスに 1 を加算) です。 並べ替えされていない arrayを使用してこのメソッドを呼び出すと、戻り値が正しくなく、arrayvalue が存在する場合でも負の数が返される可能性があります。

例外

arraynullです。

array は多次元です。

index は、arrayの下限未満です。

-又は-

length は 0 未満です。

indexlength は、arrayで有効な範囲を指定しません。

-又は-

value は、arrayの要素と互換性のない型です。

valueIComparable インターフェイスを実装せず、IComparable インターフェイスを実装していない要素が検索で検出されます。

注釈

このメソッドは、負のインデックスを含む配列の検索をサポートしていません。 array は、このメソッドを呼び出す前に並べ替える必要があります。

Array に指定した値が含まれていない場合、メソッドは負の整数を返します。 負の結果にビットごとの補数演算子 (C# では ~、Visual Basic では Not) を適用してインデックスを生成できます。 このインデックスが配列の上限より 1 大きい場合、配列内に value より大きい要素はありません。 それ以外の場合は、valueより大きい最初の要素のインデックスです。

value または array のすべての要素は、比較に使用される IComparable インターフェイスを実装する必要があります。 array の要素は、IComparable 実装によって定義された並べ替え順序に従って、値を増やして既に並べ替えられている必要があります。そうしないと、結果が正しくない可能性があります。

手記

valueIComparable インターフェイスを実装していない場合、array の要素は、検索が開始される前に IComparable テストされません。 IComparableを実装していない要素が検索で検出されると、例外がスローされます。

重複する要素を使用できます。 Arrayvalueと等しい複数の要素が含まれている場合、メソッドは 1 つの出現箇所のインデックスのみを返し、必ずしも最初の要素を返すわけではありません。

null は常に他の参照型と比較できます。そのため、null との比較では例外は生成されません。

手記

テストされるすべての要素について、value は、valuenullされている場合でも、適切な IComparable 実装に渡されます。 つまり、IComparable 実装によって、特定の要素が nullと比較する方法が決まります。

このメソッドは O(ログ n) 操作で、nlength

こちらもご覧ください

  • IComparable
  • Sort
  • 配列 での Culture-Insensitive 文字列操作の実行の

適用対象

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

ソース:
Array.cs
ソース:
Array.cs
ソース:
Array.cs

指定した IComparer インターフェイスを使用して、1 次元の並べ替えられた配列内の要素の範囲で値を検索します。

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

検索する並べ替えられた 1 次元 Array

index
Int32

検索する範囲の開始インデックス。

length
Int32

検索する範囲の長さ。

value
Object

検索するオブジェクト。

comparer
IComparer

要素を比較するときに使用する IComparer 実装。

-又は-

各要素の IComparable 実装を使用 null

戻り値

指定した array内の指定した value のインデックス (value が見つかった場合)。それ以外の場合は負の数。 value が見つからず、valuearray内の 1 つ以上の要素より小さい場合、返される負の数は、valueより大きい最初の要素のインデックスのビットごとの補数です。 value が見つからず、valuearray内のすべての要素より大きい場合、返される負の数はビットごとの補数 (最後の要素のインデックスに 1 を加算) です。 並べ替えされていない arrayを使用してこのメソッドを呼び出すと、戻り値が正しくなく、arrayvalue が存在する場合でも負の数が返される可能性があります。

例外

arraynullです。

array は多次元です。

index は、arrayの下限未満です。

-又は-

length は 0 未満です。

indexlength は、arrayで有効な範囲を指定しません。

-又は-

comparernullであり、valuearrayの要素と互換性のない型です。

comparer nullvalueIComparable インターフェイスを実装せず、IComparable インターフェイスを実装していない要素が検索で検出されます。

注釈

このメソッドは、負のインデックスを含む配列の検索をサポートしていません。 array は、このメソッドを呼び出す前に並べ替える必要があります。

Array に指定した値が含まれていない場合、メソッドは負の整数を返します。 負の結果にビットごとの補数演算子 (C# では ~、Visual Basic では Not) を適用してインデックスを生成できます。 このインデックスが配列の上限より 1 大きい場合、配列内に value より大きい要素はありません。 それ以外の場合は、valueより大きい最初の要素のインデックスです。

比較子は、要素の比較方法をカスタマイズします。 たとえば、比較子として System.Collections.CaseInsensitiveComparer を使用して、大文字と小文字を区別しない文字列検索を実行できます。

comparernullされていない場合、array の要素は、指定した IComparer 実装を使用して、指定した値と比較されます。 array の要素は、comparerで定義された並べ替え順序に従って、値を増やして並べ替える必要があります。そうしないと、結果が正しくない可能性があります。

comparernull場合、比較は、要素自体または指定された値によって提供される IComparable 実装を使用して行われます。 array の要素は、IComparable 実装によって定義された並べ替え順序に従って、値を増やして既に並べ替えられている必要があります。そうしないと、結果が正しくない可能性があります。

手記

comparernull され、valueIComparable インターフェイスを実装していない場合、array の要素は検索を開始する前に IComparable についてテストされません。 IComparableを実装していない要素が検索で検出されると、例外がスローされます。

重複する要素を使用できます。 Arrayvalueと等しい複数の要素が含まれている場合、メソッドは 1 つの出現箇所のインデックスのみを返し、必ずしも最初の要素を返すわけではありません。

null は常に他の参照型と比較できます。したがって、IComparableを使用する場合、null との比較では例外は生成されません。

手記

テストされるすべての要素について、value は、valuenullされている場合でも、適切な IComparable 実装に渡されます。 つまり、IComparable 実装によって、特定の要素が nullと比較する方法が決まります。

このメソッドは O(ログ n) 操作で、nlength

こちらもご覧ください

適用対象

BinarySearch<T>(T[], T)

ソース:
Array.cs
ソース:
Array.cs
ソース:
Array.cs

Array の各要素と指定したオブジェクトによって実装される IComparable<T> ジェネリック インターフェイスを使用して、1 次元の並べ替えられた配列全体で特定の要素を検索します。

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

検索する並べ替えられた 1 次元の 0 から始まる Array

value
T

検索するオブジェクト。

戻り値

指定した array内の指定した value のインデックス (value が見つかった場合)。それ以外の場合は負の数。 value が見つからず、valuearray内の 1 つ以上の要素より小さい場合、返される負の数は、valueより大きい最初の要素のインデックスのビットごとの補数です。 value が見つからず、valuearray内のすべての要素より大きい場合、返される負の数はビットごとの補数 (最後の要素のインデックスに 1 を加算) です。 並べ替えされていない arrayを使用してこのメソッドを呼び出すと、戻り値が正しくなく、arrayvalue が存在する場合でも負の数が返される可能性があります。

例外

arraynullです。

T では、IComparable<T> ジェネリック インターフェイスは実装されません。

次のコード例は、Sort<T>(T[]) ジェネリック メソッドのオーバーロードと BinarySearch<T>(T[], T) ジェネリック メソッドのオーバーロードを示しています。 文字列の配列は、特定の順序で作成されません。

配列が表示、並べ替え、再び表示されます。 BinarySearch メソッドを使用するには、配列を並べ替える必要があります。

手記

Visual Basic、F#、C#、および C++ は、最初の引数の型からジェネリック型パラメーターの型を推論するため、Sort および BinarySearch ジェネリック メソッドの呼び出しは、非ジェネリック メソッドの呼び出しと違いはありません。 Ildasm.exe (IL 逆アセンブラー) を使用して Microsoft Intermediate Language (MSIL) を調べると、ジェネリック メソッドが呼び出されていることがわかります。

その後、BinarySearch<T>(T[], T) ジェネリック メソッドのオーバーロードを使用して、2 つの文字列 (配列に含まれていない文字列と配列内にない文字列) を検索します。 BinarySearch メソッドの配列と戻り値は、ShowWhere ジェネリック メソッド (F# の例の showWhere 関数) に渡されます。このメソッドは、文字列が見つかった場合はインデックス値を表示し、それ以外の場合は、配列内にある場合は検索文字列の間に収まる要素を表示します。 文字列が配列にない場合、インデックスは負の値になります。そのため、ShowWhere メソッドはビットごとの補数 (C# および Visual C++ の ~ 演算子、F# の ~~~ 演算子、Visual Basic Xorでは -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# では ~、Visual Basic では Not) を適用してインデックスを生成できます。 このインデックスが配列のサイズと等しい場合、配列内に value より大きい要素はありません。 それ以外の場合は、valueより大きい最初の要素のインデックスです。

T は、比較に使用される IComparable<T> ジェネリック インターフェイスを実装する必要があります。 array の要素は、IComparable<T> 実装によって定義された並べ替え順序に従って、値を増やして既に並べ替えられている必要があります。そうしないと、結果が正しくない可能性があります。

重複する要素を使用できます。 Arrayvalueと等しい複数の要素が含まれている場合、メソッドは 1 つの出現箇所のインデックスのみを返し、必ずしも最初の要素を返すわけではありません。

null は常に他の参照型と比較できます。そのため、null との比較では例外は生成されません。

手記

テストされるすべての要素について、value は、valuenullされている場合でも、適切な IComparable<T> 実装に渡されます。 つまり、IComparable<T> 実装によって、特定の要素が nullと比較する方法が決まります。

このメソッドは O(ログ n) 操作です。ここで、narrayLength です。

こちらもご覧ください

適用対象

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

ソース:
Array.cs
ソース:
Array.cs
ソース:
Array.cs

指定した IComparer<T> ジェネリック インターフェイスを使用して、1 次元の並べ替えられた配列全体で値を検索します。

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

検索する並べ替えられた 1 次元の 0 から始まる Array

value
T

検索するオブジェクト。

comparer
IComparer<T>

要素を比較するときに使用する IComparer<T> 実装。

-又は-

各要素の IComparable<T> 実装を使用 null

戻り値

指定した array内の指定した value のインデックス (value が見つかった場合)。それ以外の場合は負の数。 value が見つからず、valuearray内の 1 つ以上の要素より小さい場合、返される負の数は、valueより大きい最初の要素のインデックスのビットごとの補数です。 value が見つからず、valuearray内のすべての要素より大きい場合、返される負の数はビットごとの補数 (最後の要素のインデックスに 1 を加算) です。 並べ替えされていない arrayを使用してこのメソッドを呼び出すと、戻り値が正しくなく、arrayvalue が存在する場合でも負の数が返される可能性があります。

例外

arraynullです。

comparernullであり、valuearrayの要素と互換性のない型です。

comparernullであり、TIComparable<T> ジェネリック インターフェイスを実装しません

次の例では、Sort<T>(T[], IComparer<T>) ジェネリック メソッドのオーバーロードと、BinarySearch<T>(T[], T, IComparer<T>) ジェネリック メソッドのオーバーロードを示します。

このコード例では、ReverseCompareという名前の文字列の代替比較子を定義します。これは、IComparer<string> (Visual Basic ではIComparer(Of String)、Visual C++ では IComparer<String^>) ジェネリック インターフェイスを実装します。 比較子は CompareTo(String) メソッドを呼び出し、比較の順序を逆にして、文字列が低から高ではなく高から低に並べ替えられるようにします。

配列が表示、並べ替え、再び表示されます。 BinarySearch メソッドを使用するには、配列を並べ替える必要があります。

手記

Visual Basic、C#、および C++ は、最初の引数の型からジェネリック型パラメーターの型を推論するため、Sort<T>(T[], IComparer<T>) および BinarySearch<T>(T[], T, IComparer<T>) ジェネリック メソッドの呼び出しは、非ジェネリック メソッドの呼び出しと違いはありません。 Ildasm.exe (IL 逆アセンブラー) を使用して Microsoft Intermediate Language (MSIL) を調べると、ジェネリック メソッドが呼び出されていることがわかります。

その後、BinarySearch<T>(T[], T, IComparer<T>) ジェネリック メソッドのオーバーロードを使用して、2 つの文字列 (配列に含まれていない文字列と配列内にない文字列) を検索します。 BinarySearch<T>(T[], T, IComparer<T>) メソッドの配列と戻り値は、ShowWhere ジェネリック メソッド (F# の例の showWhere 関数) に渡されます。このメソッドは、文字列が見つかった場合はインデックス値を表示し、それ以外の場合は、配列内にある場合は検索文字列の間に収まる要素を表示します。 文字列が配列の n でない場合、インデックスは負の値になります。そのため、ShowWhere メソッドはビットごとの補数 (C# および Visual C++ の ~ 演算子、F# では ~~~ 演算子、Visual Basic では Xor -1) を受け取り、検索文字列よりも大きいリスト内の最初の要素のインデックスを取得します。

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# では ~、Visual Basic では Not) を適用してインデックスを生成できます。 このインデックスが配列のサイズと等しい場合、配列内に value より大きい要素はありません。 それ以外の場合は、valueより大きい最初の要素のインデックスです。

比較子は、要素の比較方法をカスタマイズします。 たとえば、比較子として System.Collections.CaseInsensitiveComparer を使用して、大文字と小文字を区別しない文字列検索を実行できます。

comparernullされていない場合、array の要素は、指定した IComparer<T> ジェネリック インターフェイスの実装を使用して、指定した値と比較されます。 array の要素は、comparerで定義された並べ替え順序に従って、値を増やして並べ替える必要があります。そうしないと、結果が正しくない可能性があります。

comparernullされている場合は、Tによって提供される IComparable<T> ジェネリック インターフェイスの実装を使用して比較が行われます。 array の要素は、IComparable<T> 実装によって定義された並べ替え順序に従って、値を増やして既に並べ替えられている必要があります。そうしないと、結果が正しくない可能性があります。

手記

comparernull され、valueIComparable<T> ジェネリック インターフェイスを実装していない場合、array の要素は、検索が開始される前に IComparable<T> についてテストされません。 IComparable<T>を実装していない要素が検索で検出されると、例外がスローされます。

重複する要素を使用できます。 Arrayvalueと等しい複数の要素が含まれている場合、メソッドは 1 つの出現箇所のインデックスのみを返し、必ずしも最初の要素を返すわけではありません。

null は常に他の参照型と比較できます。そのため、null との比較では例外は生成されません。

手記

テストされるすべての要素について、value は、valuenullされている場合でも、適切な IComparable<T> 実装に渡されます。 つまり、IComparable<T> 実装によって、特定の要素が nullと比較する方法が決まります。

このメソッドは O(ログ n) 操作です。ここで、narrayLength です。

こちらもご覧ください

適用対象

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

ソース:
Array.cs
ソース:
Array.cs
ソース:
Array.cs

Array の各要素と指定した値によって実装される IComparable<T> ジェネリック インターフェイスを使用して、1 次元の並べ替えられた配列内の要素の範囲で値を検索します。

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

検索する並べ替えられた 1 次元の 0 から始まる Array

index
Int32

検索する範囲の開始インデックス。

length
Int32

検索する範囲の長さ。

value
T

検索するオブジェクト。

戻り値

指定した array内の指定した value のインデックス (value が見つかった場合)。それ以外の場合は負の数。 value が見つからず、valuearray内の 1 つ以上の要素より小さい場合、返される負の数は、valueより大きい最初の要素のインデックスのビットごとの補数です。 value が見つからず、valuearray内のすべての要素より大きい場合、返される負の数はビットごとの補数 (最後の要素のインデックスに 1 を加算) です。 並べ替えされていない arrayを使用してこのメソッドを呼び出すと、戻り値が正しくなく、arrayvalue が存在する場合でも負の数が返される可能性があります。

例外

arraynullです。

index は、arrayの下限未満です。

-又は-

length は 0 未満です。

indexlength は、arrayで有効な範囲を指定しません。

-又は-

value は、arrayの要素と互換性のない型です。

T では、IComparable<T> ジェネリック インターフェイスは実装されません。

注釈

このメソッドは、負のインデックスを含む配列の検索をサポートしていません。 array は、このメソッドを呼び出す前に並べ替える必要があります。

配列に指定した値が含まれていない場合、メソッドは負の整数を返します。 負の結果にビットごとの補数演算子 (C# では ~、Visual Basic では Not) を適用してインデックスを生成できます。 このインデックスが配列のサイズと等しい場合、配列内に value より大きい要素はありません。 それ以外の場合は、valueより大きい最初の要素のインデックスです。

T は、比較に使用される IComparable<T> ジェネリック インターフェイスを実装する必要があります。 array の要素は、IComparable<T> 実装によって定義された並べ替え順序に従って、値を増やして既に並べ替えられている必要があります。そうしないと、結果が正しくない可能性があります。

重複する要素を使用できます。 Arrayvalueと等しい複数の要素が含まれている場合、メソッドは 1 つの出現箇所のインデックスのみを返し、必ずしも最初の要素を返すわけではありません。

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> ジェネリック インターフェイスを使用して、1 次元の並べ替えられた配列内の要素の範囲で値を検索します。

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

検索する並べ替えられた 1 次元の 0 から始まる Array

index
Int32

検索する範囲の開始インデックス。

length
Int32

検索する範囲の長さ。

value
T

検索するオブジェクト。

comparer
IComparer<T>

要素を比較するときに使用する IComparer<T> 実装。

-又は-

各要素の IComparable<T> 実装を使用 null

戻り値

指定した array内の指定した value のインデックス (value が見つかった場合)。それ以外の場合は負の数。 value が見つからず、valuearray内の 1 つ以上の要素より小さい場合、返される負の数は、valueより大きい最初の要素のインデックスのビットごとの補数です。 value が見つからず、valuearray内のすべての要素より大きい場合、返される負の数はビットごとの補数 (最後の要素のインデックスに 1 を加算) です。 並べ替えされていない arrayを使用してこのメソッドを呼び出すと、戻り値が正しくなく、arrayvalue が存在する場合でも負の数が返される可能性があります。

例外

arraynullです。

index は、arrayの下限未満です。

-又は-

length は 0 未満です。

indexlength は、arrayで有効な範囲を指定しません。

-又は-

comparernullであり、valuearrayの要素と互換性のない型です。

comparernullであり、TIComparable<T> ジェネリック インターフェイスを実装しません。

注釈

このメソッドは、負のインデックスを含む配列の検索をサポートしていません。 array は、このメソッドを呼び出す前に並べ替える必要があります。

配列に指定した値が含まれていない場合、メソッドは負の整数を返します。 負の結果にビットごとの補数演算子 (C# では ~、Visual Basic では Not) を適用してインデックスを生成できます。 このインデックスが配列のサイズと等しい場合、配列内に value より大きい要素はありません。 それ以外の場合は、valueより大きい最初の要素のインデックスです。

比較子は、要素の比較方法をカスタマイズします。 たとえば、比較子として System.Collections.CaseInsensitiveComparer を使用して、大文字と小文字を区別しない文字列検索を実行できます。

comparernullされていない場合、array の要素は、指定した IComparer<T> ジェネリック インターフェイスの実装を使用して、指定した値と比較されます。 array の要素は、comparerで定義された並べ替え順序に従って、値を増やして並べ替える必要があります。そうしないと、結果が正しくない可能性があります。

comparernull場合、比較は、型 Tに対して提供される IComparable<T> ジェネリック インターフェイスの実装を使用して行われます。 array の要素は、IComparable<T> 実装によって定義された並べ替え順序に従って、値を増やして既に並べ替えられている必要があります。そうしないと、結果が正しくない可能性があります。

重複する要素を使用できます。 Arrayvalueと等しい複数の要素が含まれている場合、メソッドは 1 つの出現箇所のインデックスのみを返し、必ずしも最初の要素を返すわけではありません。

null は常に他の参照型と比較できます。したがって、IComparable<T>を使用する場合、null との比較では例外は生成されません。

手記

テストされるすべての要素について、value は、valuenullされている場合でも、適切な IComparable<T> 実装に渡されます。 つまり、IComparable<T> 実装によって、特定の要素が nullと比較する方法が決まります。

このメソッドは O(ログ n) 操作で、nlength

こちらもご覧ください

適用対象