ArrayList.BinarySearch メソッド

定義

バイナリ サーチ アルゴリズムを使用して、並べ替えられた ArrayList 内の特定の要素またはその一部を検索します。

オーバーロード

BinarySearch(Object)

既定の比較子を使用して、並べ替えられた要素の ArrayList 全体を検索し、その要素の 0 から始まるインデックスを返します。

BinarySearch(Object, IComparer)

指定した比較子を使用して、並べ替えられた要素の ArrayList 全体を検索し、その要素の 0 から始まるインデックスを返します。

BinarySearch(Int32, Int32, Object, IComparer)

指定した比較子を使用して、並べ替えられた要素の ArrayList の 1 つの要素の範囲を検索し、その要素の 0 から始まるインデックスを返します。

BinarySearch(Object)

ソース:
ArrayList.cs
ソース:
ArrayList.cs
ソース:
ArrayList.cs

既定の比較子を使用して、並べ替えられた要素の ArrayList 全体を検索し、その要素の 0 から始まるインデックスを返します。

public:
 virtual int BinarySearch(System::Object ^ value);
public virtual int BinarySearch (object value);
public virtual int BinarySearch (object? value);
abstract member BinarySearch : obj -> int
override this.BinarySearch : obj -> int
Public Overridable Function BinarySearch (value As Object) As Integer

パラメーター

value
Object

検索する Object。 値として null を指定できます。

戻り値

value が見つかった場合は、並べ替えられた ArrayList 内の value の 0 から始まるインデックス。見つからなかった場合は、負の値。これは、value の次に大きい要素のインデックスのビットごとの補数です。ただし、大きい要素が存在しない場合は、Count のビットごとの補数です。

例外

value または ArrayList の要素のいずれも IComparable インターフェイスを実装していません。

valueArrayList の要素と同じ型ではありません。

を使用 BinarySearch して 内の特定のオブジェクトを検索する方法を次のコード例に ArrayList示します。

using namespace System;
using namespace System::Collections;
void FindMyObject( ArrayList^ myList, Object^ myObject );
void PrintValues( IEnumerable^ myList );
int main()
{
   
   // Creates and initializes a new ArrayList. BinarySearch requires
   // a sorted ArrayList.
   ArrayList^ myAL = gcnew ArrayList;
   for ( int i = 0; i <= 4; i++ )
      myAL->Add( i * 2 );
   
   // Displays the ArrayList.
   Console::WriteLine( "The Int32 ArrayList contains the following:" );
   PrintValues( myAL );
   
   // Locates a specific object that does not exist in the ArrayList.
   Object^ myObjectOdd = 3;
   FindMyObject( myAL, myObjectOdd );
   
   // Locates an object that exists in the ArrayList.
   Object^ myObjectEven = 6;
   FindMyObject( myAL, myObjectEven );
}

void FindMyObject( ArrayList^ myList, Object^ myObject )
{
   int myIndex = myList->BinarySearch( 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 );
}

void PrintValues( IEnumerable^ myList )
{
   IEnumerator^ myEnum = myList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Object^ obj = safe_cast<Object^>(myEnum->Current);
      Console::Write( "   {0}", obj );
   }

   Console::WriteLine();
}

/* 
 This code produces the following output.
 
 The Int32 ArrayList contains the following:
    0   2   4   6   8
 The object to search for (3) is not found. The next larger object is at index 2.
 The object to search for (6) is at index 3.
 */
using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList. BinarySearch requires
      // a sorted ArrayList.
      ArrayList myAL = new ArrayList();
      for ( int i = 0; i <= 4; i++ )
         myAL.Add( i*2 );

      // Displays the ArrayList.
      Console.WriteLine( "The int ArrayList contains the following:" );
      PrintValues( myAL );

      // Locates a specific object that does not exist in the ArrayList.
      Object myObjectOdd = 3;
      FindMyObject( myAL, myObjectOdd );

      // Locates an object that exists in the ArrayList.
      Object myObjectEven = 6;
      FindMyObject( myAL, myObjectEven );
   }

   public static void FindMyObject( ArrayList myList, Object myObject )  {
      int myIndex=myList.BinarySearch( 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( IEnumerable myList )  {
      foreach ( Object obj in myList )
         Console.Write( "   {0}", obj );
      Console.WriteLine();
   }
}
/*
This code produces the following output.

The int ArrayList contains the following:
   0   2   4   6   8
The object to search for (3) is not found. The next larger object is at index 2.
The object to search for (6) is at index 3.
*/
Imports System.Collections

Public Class SamplesArrayList    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new ArrayList. BinarySearch requires
        ' a sorted ArrayList.
        Dim myAL As New ArrayList()
        Dim i As Integer
        For i = 0 To 4
            myAL.Add(i * 2)
        Next i 

        ' Displays the ArrayList.
        Console.WriteLine("The Int32 ArrayList contains the following:")
        PrintValues(myAL)
        
        ' Locates a specific object that does not exist in the ArrayList.
        Dim myObjectOdd As Object = 3
        FindMyObject(myAL, myObjectOdd)
        
        ' Locates an object that exists in the ArrayList.
        Dim myObjectEven As Object = 6
        FindMyObject(myAL, myObjectEven)
    End Sub    
    
    Public Shared Sub FindMyObject(myList As ArrayList, myObject As Object)
        Dim myIndex As Integer = myList.BinarySearch(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(myList As IEnumerable)
        Dim obj As [Object]
        For Each obj In  myList
            Console.Write("   {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub
    
End Class

' This code produces the following output.
' 
' The Int32 ArrayList contains the following:
'     0    2    4    6    8
' The object to search for (3) is not found. The next larger object is at index 2.
' The object to search for (6) is at index 3.

注釈

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

任意の null 型との比較は許可され、 を使用 IComparableしても例外は生成されません。 並べ替えの場合、 null は他のどのオブジェクトよりも小さいと見なされます。

ArrayList 同じ値を持つ複数の要素が含まれている場合、メソッドは 1 つの出現回数のみを返し、必ずしも最初の要素ではなく、いずれかの出現箇所を返す可能性があります。

ArrayList 指定した値が含まれていない場合、メソッドは負の整数を返します。 この負の整数にビットごとの補数演算 (~) を適用して、検索値より大きい最初の要素のインデックスを取得できます。 値を に ArrayList挿入するときは、並べ替え順序を維持するために、このインデックスを挿入ポイントとして使用する必要があります。

このメソッドは 操作です O(log n) 。ここで n 、 は Countです。

こちらもご覧ください

適用対象

BinarySearch(Object, IComparer)

ソース:
ArrayList.cs
ソース:
ArrayList.cs
ソース:
ArrayList.cs

指定した比較子を使用して、並べ替えられた要素の ArrayList 全体を検索し、その要素の 0 から始まるインデックスを返します。

public:
 virtual int BinarySearch(System::Object ^ value, System::Collections::IComparer ^ comparer);
public virtual int BinarySearch (object value, System.Collections.IComparer comparer);
public virtual int BinarySearch (object? value, System.Collections.IComparer? comparer);
abstract member BinarySearch : obj * System.Collections.IComparer -> int
override this.BinarySearch : obj * System.Collections.IComparer -> int
Public Overridable Function BinarySearch (value As Object, comparer As IComparer) As Integer

パラメーター

value
Object

検索する Object。 値として null を指定できます。

comparer
IComparer

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

- または -

各要素の IComparable 実装である既定の比較子を使用する場合は null

戻り値

value が見つかった場合は、並べ替えられた ArrayList 内の value の 0 から始まるインデックス。見つからなかった場合は、負の値。これは、value の次に大きい要素のインデックスのビットごとの補数です。ただし、大きい要素が存在しない場合は、Count のビットごとの補数です。

例外

comparernull であり、value または ArrayList の要素のいずれも IComparable インターフェイスを実装していません。

comparernull であり、valueArrayList の要素と同じ型ではありません。

次の例では、色付きの動物の を ArrayList 作成します。 指定された IComparer は、バイナリ検索の文字列比較を実行します。 反復検索とバイナリ検索の両方の結果が表示されます。

using namespace System;
using namespace System::Collections;

public ref class SimpleStringComparer : public IComparer
{
    virtual int Compare(Object^ x, Object^ y) sealed = IComparer::Compare
    {
        String^ cmpstr = (String^)x;
        return cmpstr->CompareTo((String^)y);
    }
};

public ref class MyArrayList : public ArrayList
{
public:
    static void Main()
    {
        // Creates and initializes a new ArrayList.
        MyArrayList^ coloredAnimals = gcnew MyArrayList();

        coloredAnimals->Add("White Tiger");
        coloredAnimals->Add("Pink Bunny");
        coloredAnimals->Add("Red Dragon");
        coloredAnimals->Add("Green Frog");
        coloredAnimals->Add("Blue Whale");
        coloredAnimals->Add("Black Cat");
        coloredAnimals->Add("Yellow Lion");

        // BinarySearch requires a sorted ArrayList.
        coloredAnimals->Sort();

        // Compare results of an iterative search with a binary search
        int index = coloredAnimals->IterativeSearch("White Tiger");
        Console::WriteLine("Iterative search, item found at index: {0}", index);

        index = coloredAnimals->BinarySearch("White Tiger", gcnew SimpleStringComparer());
        Console::WriteLine("Binary search, item found at index:    {0}", index);
    }

    int IterativeSearch(Object^ finditem)
    {
        int index = -1;

        for (int i = 0; i < this->Count; i++)
        {
            if (finditem->Equals(this[i]))
            {
                index = i;
                break;
            }
        }
        return index;
    }
};

int main()
{
    MyArrayList::Main();
}
//
// This code produces the following output.
//
// Iterative search, item found at index: 5
// Binary search, item found at index:    5
//
using System;
using System.Collections;

public class SimpleStringComparer : IComparer
{
    int IComparer.Compare(object x, object y)
    {
        string cmpstr = (string)x;
        return cmpstr.CompareTo((string)y);
    }
}

public class MyArrayList : ArrayList
{
    public static void Main()
    {
        // Creates and initializes a new ArrayList.
        MyArrayList coloredAnimals = new MyArrayList();

        coloredAnimals.Add("White Tiger");
        coloredAnimals.Add("Pink Bunny");
        coloredAnimals.Add("Red Dragon");
        coloredAnimals.Add("Green Frog");
        coloredAnimals.Add("Blue Whale");
        coloredAnimals.Add("Black Cat");
        coloredAnimals.Add("Yellow Lion");

        // BinarySearch requires a sorted ArrayList.
        coloredAnimals.Sort();

        // Compare results of an iterative search with a binary search
        int index = coloredAnimals.IterativeSearch("White Tiger");
        Console.WriteLine("Iterative search, item found at index: {0}", index);

        index = coloredAnimals.BinarySearch("White Tiger", new SimpleStringComparer());
        Console.WriteLine("Binary search, item found at index:    {0}", index);
    }

    public int IterativeSearch(object finditem)
    {
        int index = -1;

        for (int i = 0; i < this.Count; i++)
        {
            if (finditem.Equals(this[i]))
            {
                index = i;
                break;
            }
        }
        return index;
    }
}
//
// This code produces the following output.
//
// Iterative search, item found at index: 5
// Binary search, item found at index:    5
//
Imports System.Collections

Public Class SimpleStringComparer
    Implements IComparer

    Function Compare(x As Object, y As Object) As Integer Implements IComparer.Compare
          Dim cmpstr As String = CType(x, String)
          Return cmpstr.CompareTo(CType(y, String))
    End Function
End Class

Public Class MyArrayList
    Inherits ArrayList

    Public Shared Sub Main()
        ' Creates and initializes a new ArrayList.
        Dim coloredAnimals As New MyArrayList()

        coloredAnimals.Add("White Tiger")
        coloredAnimals.Add("Pink Bunny")
        coloredAnimals.Add("Red Dragon")
        coloredAnimals.Add("Green Frog")
        coloredAnimals.Add("Blue Whale")
        coloredAnimals.Add("Black Cat")
        coloredAnimals.Add("Yellow Lion")

        ' BinarySearch requires a sorted ArrayList.
        coloredAnimals.Sort()

        ' Compare results of an iterative search with a binary search
        Dim index As Integer = coloredAnimals.IterativeSearch("White Tiger")
        Console.WriteLine("Iterative search, item found at index: {0}", index)

        index = coloredAnimals.BinarySearch("White Tiger", New SimpleStringComparer())
        Console.WriteLine("Binary search, item found at index:    {0}", index)
    End Sub

    Public Function IterativeSearch(finditem As Object) As Integer
        Dim index As Integer = -1

        For i As Integer = 0 To MyClass.Count - 1
            If finditem.Equals(MyClass.Item(i))
                index = i
                Exit For
            End If
        Next i
        Return index
    End Function
End Class
'
' This code produces the following output.
'
' Iterative search, item found at index: 5
' Binary search, item found at index:    5
'

注釈

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

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

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

任意の null 型との比較は許可され、 を使用 IComparableしても例外は生成されません。 並べ替えの場合、 null は他のどのオブジェクトよりも小さいと見なされます。

ArrayList 同じ値を持つ複数の要素が含まれている場合、メソッドは 1 つの出現回数のみを返し、必ずしも最初の要素ではなく、いずれかの出現箇所を返す可能性があります。

ArrayList 指定した値が含まれていない場合、メソッドは負の整数を返します。 この負の整数にビットごとの補数演算 (~) を適用して、検索値より大きい最初の要素のインデックスを取得できます。 値を に ArrayList挿入するときは、並べ替え順序を維持するために、このインデックスを挿入ポイントとして使用する必要があります。

このメソッドは 操作です O(log n) 。ここで n 、 は Countです。

こちらもご覧ください

適用対象

BinarySearch(Int32, Int32, Object, IComparer)

ソース:
ArrayList.cs
ソース:
ArrayList.cs
ソース:
ArrayList.cs

指定した比較子を使用して、並べ替えられた要素の ArrayList の 1 つの要素の範囲を検索し、その要素の 0 から始まるインデックスを返します。

public:
 virtual int BinarySearch(int index, int count, System::Object ^ value, System::Collections::IComparer ^ comparer);
public virtual int BinarySearch (int index, int count, object value, System.Collections.IComparer comparer);
public virtual int BinarySearch (int index, int count, object? value, System.Collections.IComparer? comparer);
abstract member BinarySearch : int * int * obj * System.Collections.IComparer -> int
override this.BinarySearch : int * int * obj * System.Collections.IComparer -> int
Public Overridable Function BinarySearch (index As Integer, count As Integer, value As Object, comparer As IComparer) As Integer

パラメーター

index
Int32

検索範囲の開始位置を示す 0 から始まるインデックス。

count
Int32

検索する範囲の長さ。

value
Object

検索する Object。 値として null を指定できます。

comparer
IComparer

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

- または -

各要素の IComparable 実装である既定の比較子を使用する場合は null

戻り値

value が見つかった場合は、並べ替えられた ArrayList 内の value の 0 から始まるインデックス。見つからなかった場合は、負の値。これは、value の次に大きい要素のインデックスのビットごとの補数です。ただし、大きい要素が存在しない場合は、Count のビットごとの補数です。

例外

index および countArrayList において有効な範囲を表していません。

- または -

comparernull であり、value または ArrayList の要素のいずれも IComparable インターフェイスを実装していません。

comparernull であり、valueArrayList の要素と同じ型ではありません。

index が 0 未満です。

または

count が 0 未満です。

注釈

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

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

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

任意の null 型との比較は許可され、 を使用 IComparableしても例外は生成されません。 並べ替えの場合、 null は他のどのオブジェクトよりも小さいと見なされます。

ArrayList 同じ値を持つ複数の要素が含まれている場合、メソッドは 1 つの出現回数のみを返し、必ずしも最初の要素ではなく、いずれかの出現箇所を返す可能性があります。

ArrayList 指定した値が含まれていない場合、メソッドは負の整数を返します。 この負の整数にビットごとの補数演算 (~) を適用して、検索値より大きい最初の要素のインデックスを取得できます。 値を に ArrayList挿入するときは、並べ替え順序を維持するために、このインデックスを挿入ポイントとして使用する必要があります。

このメソッドは 操作です O(log n) 。ここで n 、 は countです。

こちらもご覧ください

適用対象