ArrayList.BinarySearch 메서드

정의

이진 검색 알고리즘을 사용하여 정렬된 ArrayList나 그 일부에서 특정 요소를 찾습니다.

오버로드

BinarySearch(Object)

기본 비교자를 사용하여 정렬된 전체 ArrayList에서 요소를 검색하고 요소의 인덱스(0부터 시작)를 반환합니다.

BinarySearch(Object, IComparer)

지정된 비교자를 사용하여 정렬된 전체 ArrayList에서 요소를 검색하고 요소의 인덱스(0부터 시작)를 반환합니다.

BinarySearch(Int32, Int32, Object, IComparer)

지정된 비교자를 사용하여 정렬된 ArrayList의 요소 범위에서 요소를 검색하고 요소의 인덱스(0부터 시작)를 반환합니다.

BinarySearch(Object)

Source:
ArrayList.cs
Source:
ArrayList.cs
Source:
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의 비트 보수입니다.

예외

valueArrayList의 요소 둘 다 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.

설명

value 매개 변수 및 의 ArrayList 각 요소는 비교에 IComparable 사용되는 인터페이스를 구현해야 합니다. 의 ArrayList 요소는 이미 구현에서 정의 IComparable 한 정렬 순서에 따라 증가 값으로 정렬되어야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

null 모든 형식과의 비교는 허용되며 를 사용할 IComparable때 예외를 생성하지 않습니다. 정렬할 null 때 는 다른 개체보다 작은 것으로 간주됩니다.

ArrayList 동일한 값을 가진 요소가 두 개 이상 포함된 경우 메서드는 발생 항목 중 하나만 반환하며 첫 번째 요소가 아닌 발생 중 하나를 반환할 수 있습니다.

ArrayList 지정된 값을 포함하지 않으면 메서드는 음수 정수 를 반환합니다. 이 음수 정수에 비트 보수 연산(~)을 적용하여 검색 값보다 큰 첫 번째 요소의 인덱싱을 가져올 수 있습니다. 에 값을 ArrayList삽입할 때 이 인덱스가 정렬 순서를 유지하려면 삽입 지점으로 사용해야 합니다.

이 메서드는 작업입니다 O(log n) . 여기서 n 는 입니다 Count.

추가 정보

적용 대상

BinarySearch(Object, IComparer)

Source:
ArrayList.cs
Source:
ArrayList.cs
Source:
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이고 valueArrayList의 요소 둘 다 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
'

설명

비교자는 요소를 비교하는 방법을 사용자 지정합니다. 예를 들어 instance 비교자로 사용하여 CaseInsensitiveComparer 대/소문자를 구분하지 않는 문자열 검색을 수행할 수 있습니다.

가 제공된 경우 comparerArrayList 요소는 지정된 구현을 사용하여 지정된 값과 비교됩니다 IComparer . 의 ArrayList 요소는 에 정의된 comparer정렬 순서에 따라 증가 값으로 이미 정렬되어야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

가 이nullcomparer 요소 자체 또는 지정된 값으로 제공된 구현을 사용하여 IComparable 비교가 수행됩니다. 의 ArrayList 요소는 이미 구현에서 정의 IComparable 한 정렬 순서에 따라 증가 값으로 정렬되어야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

null 모든 형식과의 비교는 허용되며 를 사용할 IComparable때 예외를 생성하지 않습니다. 정렬할 null 때 는 다른 개체보다 작은 것으로 간주됩니다.

ArrayList 동일한 값을 가진 요소가 두 개 이상 포함된 경우 메서드는 발생 항목 중 하나만 반환하며 첫 번째 요소가 아닌 발생 중 하나를 반환할 수 있습니다.

ArrayList 지정된 값을 포함하지 않으면 메서드는 음수 정수 를 반환합니다. 이 음수 정수에 비트 보수 연산(~)을 적용하여 검색 값보다 큰 첫 번째 요소의 인덱싱을 가져올 수 있습니다. 에 값을 ArrayList삽입할 때 이 인덱스가 정렬 순서를 유지하려면 삽입 지점으로 사용해야 합니다.

이 메서드는 작업입니다 O(log n) . 여기서 n 는 입니다 Count.

추가 정보

적용 대상

BinarySearch(Int32, Int32, Object, IComparer)

Source:
ArrayList.cs
Source:
ArrayList.cs
Source:
ArrayList.cs

지정된 비교자를 사용하여 정렬된 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);
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의 비트 보수입니다.

예외

indexcountArrayList의 올바른 범위를 나타내지 않습니다.

또는

comparernull이고 valueArrayList의 요소 둘 다 IComparable 인터페이스를 구현하지 않습니다.

comparernull이고 valueArrayList의 요소와 동일한 형식이 아닙니다.

index가 0보다 작은 경우

또는

count가 0보다 작은 경우

설명

비교자는 요소를 비교하는 방법을 사용자 지정합니다. 예를 들어 instance 비교자로 사용하여 CaseInsensitiveComparer 대/소문자를 구분하지 않는 문자열 검색을 수행할 수 있습니다.

가 제공된 경우 comparerArrayList 요소는 지정된 구현을 사용하여 지정된 값과 비교됩니다 IComparer . 의 ArrayList 요소는 에 정의된 comparer정렬 순서에 따라 증가 값으로 이미 정렬되어야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

가 이nullcomparer 요소 자체 또는 지정된 값으로 제공된 구현을 사용하여 IComparable 비교가 수행됩니다. 의 ArrayList 요소는 이미 구현에서 정의 IComparable 한 정렬 순서에 따라 증가 값으로 정렬되어야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

null 모든 형식과의 비교는 허용되며 를 사용할 IComparable때 예외를 생성하지 않습니다. 정렬할 null 때 는 다른 개체보다 작은 것으로 간주됩니다.

ArrayList 동일한 값을 가진 요소가 두 개 이상 포함된 경우 메서드는 발생 항목 중 하나만 반환하며 첫 번째 요소가 아닌 발생 중 하나를 반환할 수 있습니다.

ArrayList 지정된 값을 포함하지 않으면 메서드는 음수 정수 를 반환합니다. 이 음수 정수에 비트 보수 연산(~)을 적용하여 검색 값보다 큰 첫 번째 요소의 인덱싱을 가져올 수 있습니다. 에 값을 ArrayList삽입할 때 이 인덱스가 정렬 순서를 유지하려면 삽입 지점으로 사용해야 합니다.

이 메서드는 작업입니다 O(log n) . 여기서 n 는 입니다 count.

추가 정보

적용 대상