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