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)

配列の各要素および指定したオブジェクトによって実装されている 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

検索するオブジェクト。

戻り値

Int32

value が存在する場合は、指定した array における指定した value のインデックス。それ以外の場合は負の数値。 value が見つからず、valuearray 内の 1 つ以上の要素よりも小さい場合、返される負の数値は value より大きい最初の要素のインデックスのビットごとの補数となります。 value が見つからず、valuearray 内のどの要素よりも大きい場合は、返される負の数値は最後の要素のインデックス +1 のビットごとの補数となります。 並べ替えられていない array に対してこのメソッドを呼び出すと、valuearray に存在していても、戻り値が間違っている場合や、負の数値が返される場合があります。

例外

arraynullです。

array が多次元です。

value の型に array の要素との互換性がありません。

valueIComparable インターフェイスを実装しておらず、IComparable インターフェイスを実装していない要素が検索により検出されました。

次のコード例は、BinarySearchArray.

注意

配列は、その要素を昇順で並べ替え順序で作成します。 このメソッドでは 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) を負の結果に適用してインデックスを生成できます。 このインデックスが配列の上限より 1 大きい場合、配列内より value 大きい要素はありません。 それ以外の場合は、より大きい value最初の要素のインデックスです。

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

注意

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

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

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

注意

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

このメソッドは O (ログn) 操作です。これは次のarray操作nLengthです。

こちらもご覧ください

適用対象

BinarySearch(Array, Object, IComparer)

指定した 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

戻り値

Int32

value が存在する場合は、指定した array における指定した value のインデックス。それ以外の場合は負の数値。 value が見つからず、valuearray 内の 1 つ以上の要素よりも小さい場合、返される負の数値は value より大きい最初の要素のインデックスのビットごとの補数となります。 value が見つからず、valuearray 内のどの要素よりも大きい場合は、返される負の数値は最後の要素のインデックス +1 のビットごとの補数となります。 並べ替えられていない array に対してこのメソッドを呼び出すと、valuearray に存在していても、戻り値が間違っている場合や、負の数値が返される場合があります。

例外

arraynullです。

array が多次元です。

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

comparernull で、valueIComparable インターフェイスを実装しておらず、IComparable インターフェイスを実装していない要素が検索により検出されました。

注釈

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

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

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

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

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

注意

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

重複する要素を使用できます。 1 つ以上の要素が Array 含まれている場合、メソッドは 1 回だけ出現するインデックスを返し、必ずしも最初の要素 valueを返すわけではありません。

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

注意

テストされたすべての要素に対して、value適切なIComparable実装に渡されます。ただし、value null つまり、実装は IComparable 、特定の要素と比較する方法を null決定します。

このメソッドは O(logn) 操作です。これは次の操作nLengthですarray

こちらもご覧ください

適用対象

BinarySearch(Array, Int32, Int32, Object)

配列の各要素および指定した値によって実装されている 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

検索するオブジェクト。

戻り値

Int32

value が存在する場合は、指定した array における指定した value のインデックス。それ以外の場合は負の数値。 value が見つからず、valuearray 内の 1 つ以上の要素よりも小さい場合、返される負の数値は value より大きい最初の要素のインデックスのビットごとの補数となります。 value が見つからず、valuearray 内のどの要素よりも大きい場合は、返される負の数値は最後の要素のインデックス +1 のビットごとの補数となります。 並べ替えられていない array に対してこのメソッドを呼び出すと、valuearray に存在していても、戻り値が間違っている場合や、負の数値が返される場合があります。

例外

arraynullです。

array が多次元です。

indexarray の下限を下回っています。

  • または -

length が 0 未満です。

index および lengtharray の有効な範囲を指定していません。

  • または -

value の型に array の要素との互換性がありません。

valueIComparable インターフェイスを実装しておらず、IComparable インターフェイスを実装していない要素が検索により検出されました。

注釈

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

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

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

注意

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

重複する要素を使用できます。 1 つ以上の要素が Array 含まれている場合、メソッドは 1 回だけ出現するインデックスを返し、必ずしも最初の要素 valueを返すわけではありません。

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

注意

テストされたすべての要素に対して、value適切なIComparable実装に渡されます。ただし、value null つまり、実装は IComparable 、特定の要素と比較する方法を null決定します。

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

こちらもご覧ください

適用対象

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

指定した 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

戻り値

Int32

value が存在する場合は、指定した array における指定した value のインデックス。それ以外の場合は負の数値。 value が見つからず、valuearray 内の 1 つ以上の要素よりも小さい場合、返される負の数値は value より大きい最初の要素のインデックスのビットごとの補数となります。 value が見つからず、valuearray 内のどの要素よりも大きい場合は、返される負の数値は最後の要素のインデックス +1 のビットごとの補数となります。 並べ替えられていない array に対してこのメソッドを呼び出すと、valuearray に存在していても、戻り値が間違っている場合や、負の数値が返される場合があります。

例外

arraynullです。

array が多次元です。

indexarray の下限を下回っています。

  • または -

length が 0 未満です。

index および lengtharray の有効な範囲を指定していません。

  • または -

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

comparernull で、valueIComparable インターフェイスを実装しておらず、IComparable インターフェイスを実装していない要素が検索により検出されました。

注釈

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

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

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

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

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

注意

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

重複する要素を使用できます。 1 つ以上の要素が Array 含まれている場合、メソッドは 1 回だけ出現するインデックスを返し、必ずしも最初の要素 valueを返すわけではありません。

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

注意

テストされたすべての要素に対して、value適切なIComparable実装に渡されます。ただし、value null つまり、実装は IComparable 、特定の要素と比較する方法を null決定します。

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

こちらもご覧ください

適用対象

BinarySearch<T>(T[], T)

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 次元の Array。インデックス番号は 0 から始まります。

value
T

検索するオブジェクト。

戻り値

Int32

value が存在する場合は、指定した array における指定した value のインデックス。それ以外の場合は負の数値。 value が見つからず、valuearray 内の 1 つ以上の要素よりも小さい場合、返される負の数値は value より大きい最初の要素のインデックスのビットごとの補数となります。 value が見つからず、valuearray 内のどの要素よりも大きい場合は、返される負の数値は最後の要素のインデックス +1 のビットごとの補数となります。 並べ替えられていない array に対してこのメソッドを呼び出すと、valuearray に存在していても、戻り値が間違っている場合や、負の数値が返される場合があります。

例外

arraynullです。

T は、IComparable<T> ジェネリック インターフェイスを実装していません。

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

配列が表示され、並べ替えられて、もう一度表示されます。 メソッドを使用 BinarySearch するには、配列を並べ替える必要があります。

注意

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

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

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>並べ替える必要があります。それ以外の場合は、結果が正しくない可能性があります。

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

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

注意

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

このメソッドは O (ログn) 操作です。これは次のarray操作nLengthです。

こちらもご覧ください

適用対象

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

指定した 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 次元の Array。インデックス番号は 0 から始まります。

value
T

検索するオブジェクト。

comparer
IComparer<T>

要素を比較する場合に使用する IComparer<T> の実装。

  • または -

各要素の IComparable<T> 実装を使用する場合は null

戻り値

Int32

value が存在する場合は、指定した array における指定した value のインデックス。それ以外の場合は負の数値。 value が見つからず、valuearray 内の 1 つ以上の要素よりも小さい場合、返される負の数値は value より大きい最初の要素のインデックスのビットごとの補数となります。 value が見つからず、valuearray 内のどの要素よりも大きい場合は、返される負の数値は最後の要素のインデックス +1 のビットごとの補数となります。 並べ替えられていない array に対してこのメソッドを呼び出すと、valuearray に存在していても、戻り値が間違っている場合や、負の数値が返される場合があります。

例外

arraynullです。

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

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

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

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

配列が表示され、並べ替えられて、もう一度表示されます。 メソッドを使用 BinarySearch するには、配列を並べ替える必要があります。

注意

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

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

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

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

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

注意

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

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

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

注意

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

このメソッドは O (ログn) 操作です。これは次のarray操作nLengthです。

こちらもご覧ください

適用対象

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

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 次元の Array。インデックス番号は 0 から始まります。

index
Int32

検索範囲の開始位置を示すインデックス。

length
Int32

検索する範囲の長さ。

value
T

検索するオブジェクト。

戻り値

Int32

value が存在する場合は、指定した array における指定した value のインデックス。それ以外の場合は負の数値。 value が見つからず、valuearray 内の 1 つ以上の要素よりも小さい場合、返される負の数値は value より大きい最初の要素のインデックスのビットごとの補数となります。 value が見つからず、valuearray 内のどの要素よりも大きい場合は、返される負の数値は最後の要素のインデックス +1 のビットごとの補数となります。 並べ替えられていない array に対してこのメソッドを呼び出すと、valuearray に存在していても、戻り値が間違っている場合や、負の数値が返される場合があります。

例外

arraynullです。

indexarray の下限を下回っています。

  • または -

length が 0 未満です。

index および lengtharray の有効な範囲を指定していません。

  • または -

value の型に array の要素との互換性がありません。

T は、IComparable<T> ジェネリック インターフェイスを実装していません。

注釈

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

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

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

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

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

注意

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

このメソッドは O(log n) 操作です。ここで n 指定します length

こちらもご覧ください

適用対象

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

指定した 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 次元の Array。インデックス番号は 0 から始まります。

index
Int32

検索範囲の開始位置を示すインデックス。

length
Int32

検索する範囲の長さ。

value
T

検索するオブジェクト。

comparer
IComparer<T>

要素を比較する場合に使用する IComparer<T> の実装。

  • または -

各要素の IComparable<T> 実装を使用する場合は null

戻り値

Int32

value が存在する場合は、指定した array における指定した value のインデックス。それ以外の場合は負の数値。 value が見つからず、valuearray 内の 1 つ以上の要素よりも小さい場合、返される負の数値は value より大きい最初の要素のインデックスのビットごとの補数となります。 value が見つからず、valuearray 内のどの要素よりも大きい場合は、返される負の数値は最後の要素のインデックス +1 のビットごとの補数となります。 並べ替えられていない array に対してこのメソッドを呼び出すと、valuearray に存在していても、戻り値が間違っている場合や、負の数値が返される場合があります。

例外

arraynullです。

indexarray の下限を下回っています。

  • または -

length が 0 未満です。

index および lengtharray の有効な範囲を指定していません。

  • または -

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

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

注釈

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

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

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

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

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

重複する要素を使用できます。 1 つ以上の要素が Array 含まれている場合、メソッドは 1 回だけ出現するインデックスを返し、必ずしも最初の要素 valueを返すわけではありません。

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

注意

テストされたすべての要素に対して、value適切なIComparable<T>実装に渡されます。ただし、value null つまり、実装は IComparable<T> 、特定の要素と比較する方法を null決定します。

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

こちらもご覧ください

適用対象