ArrayList.BinarySearch メソッド

定義

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

オーバーロード

名前 説明
BinarySearch(Object)

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

BinarySearch(Object, IComparer)

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

BinarySearch(Int32, Int32, Object, IComparer)

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

BinarySearch(Object)

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

public:
 virtual int BinarySearch(System::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できます。

返品

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

例外

valueArrayListの要素も、IComparable インターフェイスを実装しません。

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

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

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.

注釈

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

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

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

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

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

こちらもご覧ください

適用対象

BinarySearch(Object, IComparer)

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

public:
 virtual int BinarySearch(System::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 実装。

-または-

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

返品

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

例外

comparernullであり、IComparable インターフェイスを実装ArrayListvalueも要素もありません。

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

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

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で定義された並べ替え順序に従って値を増やす必要があります。それ以外の場合は、結果が正しくない可能性があります。

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

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

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

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

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

こちらもご覧ください

適用対象

BinarySearch(Int32, Int32, Object, IComparer)

指定した比較子を使用して、並べ替えられた ArrayList 内の要素の範囲を検索し、要素の 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);
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 実装。

-または-

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

返品

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

例外

index countは、ArrayListの有効な範囲を示していません。

-または-

comparernullであり、IComparable インターフェイスを実装ArrayListvalueも要素もありません。

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

index が 0 未満です。

-または-

count が 0 未満です。

注釈

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

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

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

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

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

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

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

こちらもご覧ください

適用対象