ArrayList.BinarySearch 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
이진 검색 알고리즘을 사용하여 정렬된 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);
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가 있는 경우 정렬된 ArrayList에 있는 value의 0부터 시작하는 인덱스이고, 그렇지 않은 경우 value보다 큰 다음 요소의 인덱스에 대한 비트 보수인 음수이고, 더 큰 요소가 없는 경우 Count의 비트 보수입니다.
예외
value와 ArrayList의 요소 둘 다 IComparable 인터페이스를 구현하지 않습니다.
value가 ArrayList의 요소와 동일한 형식이 아닙니다.
예제
다음 코드 예제에서는 에서 특정 개체를 찾는 데 사용 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)
지정된 비교자를 사용하여 정렬된 전체 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가 있는 경우 정렬된 ArrayList에 있는 value의 0부터 시작하는 인덱스이고, 그렇지 않은 경우 value보다 큰 다음 요소의 인덱스에 대한 비트 보수인 음수이고, 더 큰 요소가 없는 경우 Count의 비트 보수입니다.
예외
comparer가 null이고 value 및 ArrayList의 요소 둘 다 IComparable 인터페이스를 구현하지 않습니다.
comparer가 null이고 value가 ArrayList의 요소와 동일한 형식이 아닙니다.
예제
다음 예제에서는 색이 지정된 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 지정된 값과 요소를 비교합니다. 정의한 정렬 순서comparer에 ArrayList 따라 값을 늘리기 위해 요소의 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.
이 null경우 comparer 요소 자체 또는 지정된 값으로 제공된 구현을 사용하여 IComparable 비교가 수행됩니다. 구현에서 ArrayList 정의 IComparable 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.
null 모든 형식과의 비교는 허용되며 사용 IComparable시 예외를 생성하지 않습니다. 정렬할 null 때 다른 개체보다 작은 것으로 간주됩니다.
값이 ArrayList 같은 요소가 두 개 이상 포함된 경우 메서드는 발생 중 하나만 반환하며 첫 번째 요소가 아닌 발생 중 하나만 반환할 수 있습니다.
지정된 값이 ArrayList 없으면 메서드는 음수 정수로 반환합니다. 이 음수 정수에 비트 보수 연산(~)을 적용하여 검색 값보다 큰 첫 번째 요소의 인덱스도 가져올 수 있습니다. 값을 ArrayList삽입할 때 정렬 순서를 유지하기 위해 이 인덱스가 삽입 지점으로 사용되어야 합니다.
이 메서드는 O(log n) 작업입니다 n Count.
추가 정보
적용 대상
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);
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가 있는 경우 정렬된 ArrayList에 있는 value의 0부터 시작하는 인덱스이고, 그렇지 않은 경우 value보다 큰 다음 요소의 인덱스에 대한 비트 보수인 음수이고, 더 큰 요소가 없는 경우 Count의 비트 보수입니다.
예외
index 및 count가 ArrayList의 올바른 범위를 나타내지 않습니다.
또는
comparer가 null이고 value 및 ArrayList의 요소 둘 다 IComparable 인터페이스를 구현하지 않습니다.
comparer가 null이고 value가 ArrayList의 요소와 동일한 형식이 아닙니다.
설명
비교자는 요소를 비교하는 방법을 사용자 지정합니다. 예를 들어 인스턴스를 비교자로 CaseInsensitiveComparer 사용하여 대/소문자를 구분하지 않는 문자열 검색을 수행할 수 있습니다.
제공된 경우 comparer 지정된 구현을 ArrayList 사용하여 IComparer 지정된 값과 요소를 비교합니다. 정의한 정렬 순서comparer에 ArrayList 따라 값을 늘리기 위해 요소의 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.
이 null경우 comparer 요소 자체 또는 지정된 값으로 제공된 구현을 사용하여 IComparable 비교가 수행됩니다. 구현에서 ArrayList 정의 IComparable 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.
null 모든 형식과의 비교는 허용되며 사용 IComparable시 예외를 생성하지 않습니다. 정렬할 null 때 다른 개체보다 작은 것으로 간주됩니다.
값이 ArrayList 같은 요소가 두 개 이상 포함된 경우 메서드는 발생 중 하나만 반환하며 첫 번째 요소가 아닌 발생 중 하나만 반환할 수 있습니다.
지정된 값이 ArrayList 없으면 메서드는 음수 정수로 반환합니다. 이 음수 정수에 비트 보수 연산(~)을 적용하여 검색 값보다 큰 첫 번째 요소의 인덱스도 가져올 수 있습니다. 값을 ArrayList삽입할 때 정렬 순서를 유지하기 위해 이 인덱스가 삽입 지점으로 사용되어야 합니다.
이 메서드는 O(log n) 작업입니다 n count.