Array.BinarySearch 메서드

정의

이진 검색 알고리즘을 사용하여 1차원으로 정렬된 Array에서 값을 검색합니다.

오버로드

BinarySearch(Array, Object)

배열의 각 요소 및 지정한 개체에서 구현되는 IComparable 인터페이스를 사용하여 1차원으로 정렬된 배열에서 특정 요소를 검색합니다.

BinarySearch(Array, Object, IComparer)

지정한 IComparer 인터페이스를 사용하여 1차원으로 정렬된 전체 배열에서 값을 검색합니다.

BinarySearch(Array, Int32, Int32, Object)

배열의 각 요소 및 지정한 값에서 구현되는 IComparable 인터페이스를 사용하여 1차원으로 정렬된 배열의 요소 범위에서 값을 검색합니다.

BinarySearch(Array, Int32, Int32, Object, IComparer)

지정한 IComparer 인터페이스를 사용하여 1차원으로 정렬된 배열의 요소 범위에서 값을 검색합니다.

BinarySearch<T>(T[], T)

Array의 각 요소 및 지정한 개체에서 구현되는 IComparable<T> 제네릭 인터페이스를 사용하여 1차원으로 정렬된 전체 배열에서 특정 요소를 검색합니다.

BinarySearch<T>(T[], T, IComparer<T>)

지정한 IComparer<T> 제네릭 인터페이스를 사용하여 1차원으로 정렬된 전체 배열에서 값을 검색합니다.

BinarySearch<T>(T[], Int32, Int32, T)

Array의 각 요소 및 지정한 값에서 구현되는 IComparable<T> 제네릭 인터페이스를 사용하여 1차원으로 정렬된 배열의 요소 범위에서 값을 검색합니다.

BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)

지정한 IComparer<T> 제네릭 인터페이스를 사용하여 1차원으로 정렬된 배열의 요소 범위에서 값을 검색합니다.

BinarySearch(Array, Object)

배열의 각 요소 및 지정한 개체에서 구현되는 IComparable 인터페이스를 사용하여 1차원으로 정렬된 배열에서 특정 요소를 검색합니다.

public:
 static int BinarySearch(Array ^ array, System::Object ^ value);
public static int BinarySearch (Array array, object value);
public static int BinarySearch (Array array, object? value);
static member BinarySearch : Array * obj -> int
Public Shared Function BinarySearch (array As Array, value As Object) As Integer

매개 변수

array
Array

검색할 1차원으로 정렬된 Array입니다.

value
Object

검색할 개체입니다.

반환

Int32

value가 있는 경우 지정된 array에 있는 지정된 value의 인덱스이고, 그렇지 않으면 음수입니다. value가 없고 valuearray에 있는 하나 이상의 요소보다 작은 경우 value보다 큰 첫째 요소 인덱스의 비트 보수인 음수가 반환됩니다. value가 없고 valuearray에 있는 모든 요소보다 큰 경우 마지막 요소에 1을 더한 인덱스의 비트 보수인 음수가 반환됩니다. 이 메서드가 정렬되지 않은 array를 사용하여 호출되면 valuearray에 있더라도 반환 값이 올바르지 않고 음수가 반환될 수 있습니다.

예외

array이(가) null인 경우

array가 다차원 배열인 경우

value의 형식이 array의 요소와 호환되지 않는 형식입니다.

valueIComparable 인터페이스를 구현하지 않으며 검색 중에 IComparable 인터페이스를 구현하지 않는 요소가 발견되었습니다.

예제

다음 코드 예제에서는 특정 개체를 찾는 데 사용 BinarySearch 하는 방법을 보여 있습니다 Array.

참고

배열은 해당 요소를 오름차순으로 생성합니다. 이 BinarySearch 메서드를 사용하려면 배열을 오름차순으로 정렬해야 합니다.

using namespace System;

public ref class SamplesArray
{
public:
    static void Main()
    {
        // Creates and initializes a new Array.
        Array^ myIntArray = Array::CreateInstance(Int32::typeid, 5);

        myIntArray->SetValue(8, 0);
        myIntArray->SetValue(2, 1);
        myIntArray->SetValue(6, 2);
        myIntArray->SetValue(3, 3);
        myIntArray->SetValue(7, 4);

        // Do the required sort first
        Array::Sort(myIntArray);

        // Displays the values of the Array.
        Console::WriteLine("The Int32 array contains the following:");
        PrintValues(myIntArray);

        // Locates a specific object that does not exist in the Array.
        Object^ myObjectOdd = 1;
        FindMyObject(myIntArray, myObjectOdd);

        // Locates an object that exists in the Array.
        Object^ myObjectEven = 6;
        FindMyObject(myIntArray, myObjectEven);
    }

    static void FindMyObject(Array^ myArr, Object^ myObject)
    {
        int myIndex = Array::BinarySearch(myArr, 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);
        }
    }

    static void PrintValues(Array^ myArr)
    {
        int i = 0;
        int cols = myArr->GetLength(myArr->Rank - 1);
        for each (Object^ o in myArr)
        {
            if ( i < cols )
            {
                i++;
            }
            else
            {
                Console::WriteLine();
                i = 1;
            }
            Console::Write("\t{0}", o);
        }
        Console::WriteLine();
    }
};

int main()
{
    SamplesArray::Main();
}
// This code produces the following output.
//
//The Int32 array contains the following:
//        2       3       6       7       8
//The object to search for (1) is not found. The next larger object is at index 0
//
//The object to search for (6) is at index 2.
open System

let printValues (myArray: Array) =
    let mutable i = 0
    let cols = myArray.GetLength(myArray.Rank - 1)
    for item in myArray do
        if i < cols then
            i <- i + 1
        else
            printfn ""
            i <- 1;
        printf $"\t{item}"
    printfn ""

let findMyObject (myArr: Array) (myObject: obj) =
    let myIndex = Array.BinarySearch(myArr, myObject)
    if myIndex < 0 then
        printfn $"The object to search for ({myObject}) is not found. The next larger object is at index {~~~myIndex}."
    else
        printfn $"The object to search for ({myObject}) is at index {myIndex}."

// Creates and initializes a new Array.
let myIntArray = [| 8; 2; 6; 3; 7 |]

// Do the required sort first
Array.Sort myIntArray

// Displays the values of the Array.
printfn "The int array contains the following:"
printValues myIntArray

// Locates a specific object that does not exist in the Array.
let myObjectOdd: obj = 1
findMyObject myIntArray myObjectOdd 

// Locates an object that exists in the Array.
let myObjectEven: obj = 6
findMyObject myIntArray myObjectEven
       
// This code produces the following output:
//     The int array contains the following:
//             2       3       6       7       8
//     The object to search for (1) is not found. The next larger object is at index 0.
//     The object to search for (6) is at index 2.
using System;

public class SamplesArray
{
    public static void Main()
    {
        // Creates and initializes a new Array.
        Array myIntArray = Array.CreateInstance(typeof(int), 5);

        myIntArray.SetValue(8, 0);
        myIntArray.SetValue(2, 1);
        myIntArray.SetValue(6, 2);
        myIntArray.SetValue(3, 3);
        myIntArray.SetValue(7, 4);

        // Do the required sort first
        Array.Sort(myIntArray);

        // Displays the values of the Array.
        Console.WriteLine( "The int array contains the following:" );
        PrintValues(myIntArray);

        // Locates a specific object that does not exist in the Array.
        object myObjectOdd = 1;
        FindMyObject( myIntArray, myObjectOdd );

        // Locates an object that exists in the Array.
        object myObjectEven = 6;
        FindMyObject(myIntArray, myObjectEven);
    }

    public static void FindMyObject(Array myArr, object myObject)
    {
        int myIndex=Array.BinarySearch(myArr, 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(Array myArr)
    {
        int i = 0;
        int cols = myArr.GetLength(myArr.Rank - 1);
        foreach (object o in myArr)
        {
            if ( i < cols )
            {
                i++;
            }
            else
            {
                Console.WriteLine();
                i = 1;
            }
            Console.Write( "\t{0}", o);
        }
        Console.WriteLine();
    }
}
// This code produces the following output.
//
//The int array contains the following:
//        2       3       6       7       8
//The object to search for (1) is not found. The next larger object is at index 0
//
//The object to search for (6) is at index 2.
Public Class SamplesArray
    Public Shared Sub Main()
        ' Creates and initializes a new Array.
        Dim myIntArray As Array = Array.CreateInstance( GetType(Int32), 5 )

        myIntArray.SetValue( 8, 0 )
        myIntArray.SetValue( 2, 1 )
        myIntArray.SetValue( 6, 2 )
        myIntArray.SetValue( 3, 3 )
        myIntArray.SetValue( 7, 4 )

        ' Do the required sort first
        Array.Sort(myIntArray)

        ' Displays the values of the Array.
        Console.WriteLine("The Int32 array contains the following:")
        PrintValues(myIntArray)

        ' Locates a specific object that does not exist in the Array.
        Dim myObjectOdd As Object = 1
        FindMyObject(myIntArray, myObjectOdd)

        ' Locates an object that exists in the Array.
        Dim myObjectEven As Object = 6
        FindMyObject(myIntArray, myObjectEven)
    End Sub

    Public Shared Sub FindMyObject(myArr As Array, myObject As Object)
        Dim myIndex As Integer = Array.BinarySearch(myArr, 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(myArr As Array)
        Dim i As Integer = 0
        Dim cols As Integer = myArr.GetLength( myArr.Rank - 1 )
        For Each o As Object In myArr
            If i < cols Then
                i += 1
            Else
                Console.WriteLine()
                i = 1
            End If
            Console.Write( vbTab + "{0}", o)
        Next o
        Console.WriteLine()
    End Sub
End Class
' This code produces the following output.
'
' The Int32 array contains the following:
'         2       3       6       7       8
' The object to search for (1) is not found. The next larger object is at index 0
'
' The object to search for (6) is at index 2.

설명

이 메서드는 음수 인덱스를 포함하는 배열 검색을 지원하지 않습니다. array 이 메서드를 호출하기 전에 정렬해야 합니다.

지정된 값이 Array 없으면 메서드는 음수 정수 값을 반환합니다. 비트 보수 연산자(C#의 Not 경우~ Visual Basic)를 음수 결과에 적용하여 인덱스 생성할 수 있습니다. 이 인덱스가 배열의 상한보다 큰 경우 배열보다 value 큰 요소는 없습니다. 그렇지 않으면 첫 번째 요소의 인덱스가 .보다 value큰 인덱스입니다.

또는 value 모든 요소는 array 비교에 사용되는 인터페이스를 IComparable 구현해야 합니다. array 구현에서 정의 IComparable 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

참고

value 인터페이스를 IComparable 구현하지 않으면 검색이 시작되기 전에 해당 array 요소가 테스트 IComparable 되지 않습니다. 검색에서 구현 IComparable하지 않는 요소가 발견되면 예외가 throw됩니다.

중복 요소가 허용됩니다. Array 두 개 이상의 요소가 같은 value경우 메서드는 발생 중 하나의 인덱스만 반환하며 반드시 첫 번째 요소가 아닌 인덱스를 반환합니다.

null 항상 다른 참조 형식과 비교할 수 있습니다. 따라서 비교는 예외를 null 생성하지 않습니다.

참고

테스트된 value 모든 요소에 대해 해당 IComparable 구현에 전달됩니다null(있는 경우에도value). 즉, 구현은 IComparable 지정된 요소와 비교하는 방법을 결정합니다 null.

이 메서드는 O(로그n) 연산이며 여기서 nLength array

추가 정보

적용 대상

BinarySearch(Array, Object, IComparer)

지정한 IComparer 인터페이스를 사용하여 1차원으로 정렬된 전체 배열에서 값을 검색합니다.

public:
 static int BinarySearch(Array ^ array, System::Object ^ value, System::Collections::IComparer ^ comparer);
public static int BinarySearch (Array array, object value, System.Collections.IComparer comparer);
public static int BinarySearch (Array array, object? value, System.Collections.IComparer? comparer);
static member BinarySearch : Array * obj * System.Collections.IComparer -> int
Public Shared Function BinarySearch (array As Array, value As Object, comparer As IComparer) As Integer

매개 변수

array
Array

검색할 1차원으로 정렬된 Array입니다.

value
Object

검색할 개체입니다.

comparer
IComparer

요소를 비교할 때 사용하는 IComparer 구현입니다.

또는

각 요소의 IComparable 구현을 사용할 null입니다.

반환

Int32

value가 있는 경우 지정된 array에 있는 지정된 value의 인덱스이고, 그렇지 않으면 음수입니다. value가 없고 valuearray에 있는 하나 이상의 요소보다 작은 경우 value보다 큰 첫째 요소 인덱스의 비트 보수인 음수가 반환됩니다. value가 없고 valuearray에 있는 모든 요소보다 큰 경우 마지막 요소에 1을 더한 인덱스의 비트 보수인 음수가 반환됩니다. 이 메서드가 정렬되지 않은 array를 사용하여 호출되면 valuearray에 있더라도 반환 값이 올바르지 않고 음수가 반환될 수 있습니다.

예외

array이(가) null인 경우

array가 다차원 배열인 경우

comparernull이고 valuearray의 요소와 호환되지 않는 형식입니다.

comparernull이고, valueIComparable 인터페이스를 구현하지 않으며 검색 중에 IComparable 인터페이스를 구현하지 않는 요소가 발견되었습니다.

설명

이 메서드는 음수 인덱스를 포함하는 배열 검색을 지원하지 않습니다. array 이 메서드를 호출하기 전에 정렬해야 합니다.

지정된 값이 Array 없으면 메서드는 음수 정수 값을 반환합니다. 비트 보수 연산자(C#의 Not 경우~ Visual Basic)를 음수 결과에 적용하여 인덱스 생성할 수 있습니다. 이 인덱스가 배열의 상한보다 큰 경우 배열보다 value 큰 요소는 없습니다. 그렇지 않으면 첫 번째 요소의 인덱스가 .보다 value큰 경우

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

그렇지 않은 null경우 comparer 지정된 구현을 사용하여 IComparer 지정된 값과 요소를 array 비교합니다. 정의 array 한 정렬 순서 comparer에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

null경우comparer 요소 자체 또는 지정된 값으로 제공된 구현을 사용하여 IComparable 비교가 수행됩니다. array 구현에서 정의 IComparable 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

참고

인터페이스를 null value 구현 IComparable 하지 않는 경우 comparer 검색이 시작되기 전에 해당 요소가 array 테스트 IComparable 되지 않습니다. 검색에서 구현 IComparable하지 않는 요소를 발견하면 예외가 throw됩니다.

중복 요소가 허용됩니다. Array 두 개 이상의 요소가 같은 value경우 메서드는 발생 중 하나의 인덱스만 반환하고 반드시 첫 번째 요소의 인덱스를 반환하지는 않습니다.

null 항상 다른 참조 형식과 비교할 수 있습니다. 따라서 비교는 예외를 null 생성하지 않습니다.

참고

테스트된 value 모든 요소에 대해 적절한 IComparable 구현에 전달됩니다null(있는 경우)value. 즉, 구현은 IComparable 지정된 요소와 비교하는 방법을 결정합니다 null.

이 메서드는 O(logn) 연산이며 여기서 n 는 .입니다arrayLength.

추가 정보

적용 대상

BinarySearch(Array, Int32, Int32, Object)

배열의 각 요소 및 지정한 값에서 구현되는 IComparable 인터페이스를 사용하여 1차원으로 정렬된 배열의 요소 범위에서 값을 검색합니다.

public:
 static int BinarySearch(Array ^ array, int index, int length, System::Object ^ value);
public static int BinarySearch (Array array, int index, int length, object value);
public static int BinarySearch (Array array, int index, int length, object? value);
static member BinarySearch : Array * int * int * obj -> int
Public Shared Function BinarySearch (array As Array, index As Integer, length As Integer, value As Object) As Integer

매개 변수

array
Array

검색할 1차원으로 정렬된 Array입니다.

index
Int32

검색할 범위의 시작 인덱스입니다.

length
Int32

검색할 범위의 길이입니다.

value
Object

검색할 개체입니다.

반환

Int32

value가 있는 경우 지정된 array에 있는 지정된 value의 인덱스이고, 그렇지 않으면 음수입니다. value가 없고 valuearray에 있는 하나 이상의 요소보다 작은 경우 value보다 큰 첫째 요소 인덱스의 비트 보수인 음수가 반환됩니다. value가 없고 valuearray에 있는 모든 요소보다 큰 경우 마지막 요소에 1을 더한 인덱스의 비트 보수인 음수가 반환됩니다. 이 메서드가 정렬되지 않은 array를 사용하여 호출되면 valuearray에 있더라도 반환 값이 올바르지 않고 음수가 반환될 수 있습니다.

예외

array이(가) null인 경우

array가 다차원 배열인 경우

indexarray의 하한값보다 작습니다.

또는

length가 0보다 작은 경우

indexlengtharray의 올바른 범위를 지정하지 않습니다.

또는

value의 형식이 array의 요소와 호환되지 않는 형식입니다.

valueIComparable 인터페이스를 구현하지 않으며 검색 중에 IComparable 인터페이스를 구현하지 않는 요소가 발견되었습니다.

설명

이 메서드는 음수 인덱스를 포함하는 배열 검색을 지원하지 않습니다. array 이 메서드를 호출하기 전에 정렬해야 합니다.

지정된 값이 Array 없으면 메서드는 음수 정수로 반환합니다. 음수 결과에 비트 보수 연산자(C#의 경우~, Not Visual Basic)를 적용하여 인덱스 생성할 수 있습니다. 이 인덱스가 배열의 상한보다 큰 경우 배열보다 value 큰 요소는 없습니다. 그렇지 않으면 첫 번째 요소의 인덱스가 .보다 value큰 경우

둘 중 하나 value 또는 모든 요소는 array 비교에 IComparable 사용되는 인터페이스를 구현해야 합니다. array 구현에서 정의 IComparable 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

참고

value 인터페이스를 IComparable 구현하지 않으면 검색이 시작되기 전에 해당 array 요소가 테스트 IComparable 되지 않습니다. 검색에서 구현 IComparable하지 않는 요소를 발견하면 예외가 throw됩니다.

중복 요소가 허용됩니다. Array 두 개 이상의 요소가 같은 value경우 메서드는 발생 중 하나의 인덱스만 반환하고 반드시 첫 번째 요소의 인덱스를 반환하지는 않습니다.

null 항상 다른 참조 형식과 비교할 수 있습니다. 따라서 비교는 예외를 null 생성하지 않습니다.

참고

테스트된 value 모든 요소에 대해 적절한 IComparable 구현에 전달됩니다null(있는 경우)value. 즉, 구현은 IComparable 지정된 요소와 비교하는 방법을 결정합니다 null.

이 메서드는 O(로그 n) 작업 n 입니다 length.

추가 정보

적용 대상

BinarySearch(Array, Int32, Int32, Object, IComparer)

지정한 IComparer 인터페이스를 사용하여 1차원으로 정렬된 배열의 요소 범위에서 값을 검색합니다.

public:
 static int BinarySearch(Array ^ array, int index, int length, System::Object ^ value, System::Collections::IComparer ^ comparer);
public static int BinarySearch (Array array, int index, int length, object value, System.Collections.IComparer comparer);
public static int BinarySearch (Array array, int index, int length, object? value, System.Collections.IComparer? comparer);
static member BinarySearch : Array * int * int * obj * System.Collections.IComparer -> int
Public Shared Function BinarySearch (array As Array, index As Integer, length As Integer, value As Object, comparer As IComparer) As Integer

매개 변수

array
Array

검색할 1차원으로 정렬된 Array입니다.

index
Int32

검색할 범위의 시작 인덱스입니다.

length
Int32

검색할 범위의 길이입니다.

value
Object

검색할 개체입니다.

comparer
IComparer

요소를 비교할 때 사용하는 IComparer 구현입니다.

또는

각 요소의 IComparable 구현을 사용할 null입니다.

반환

Int32

value가 있는 경우 지정된 array에 있는 지정된 value의 인덱스이고, 그렇지 않으면 음수입니다. value가 없고 valuearray에 있는 하나 이상의 요소보다 작은 경우 value보다 큰 첫째 요소 인덱스의 비트 보수인 음수가 반환됩니다. value가 없고 valuearray에 있는 모든 요소보다 큰 경우 마지막 요소에 1을 더한 인덱스의 비트 보수인 음수가 반환됩니다. 이 메서드가 정렬되지 않은 array를 사용하여 호출되면 valuearray에 있더라도 반환 값이 올바르지 않고 음수가 반환될 수 있습니다.

예외

array이(가) null인 경우

array가 다차원 배열인 경우

indexarray의 하한값보다 작습니다.

또는

length가 0보다 작은 경우

indexlengtharray의 올바른 범위를 지정하지 않습니다.

또는

comparernull이고 valuearray의 요소와 호환되지 않는 형식입니다.

comparernull이고, valueIComparable 인터페이스를 구현하지 않으며 검색 중에 IComparable 인터페이스를 구현하지 않는 요소가 발견되었습니다.

설명

이 메서드는 음수 인덱스를 포함하는 배열 검색을 지원하지 않습니다. array 이 메서드를 호출하기 전에 정렬해야 합니다.

지정된 값이 Array 없으면 메서드는 음수 정수로 반환합니다. 음수 결과에 비트 보수 연산자(C#의 경우~, Not Visual Basic)를 적용하여 인덱스 생성할 수 있습니다. 이 인덱스가 배열의 상한보다 큰 경우 배열보다 value 큰 요소는 없습니다. 그렇지 않으면 첫 번째 요소의 인덱스가 .보다 value큰 경우

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

그렇지 않은 null경우 comparer 지정된 구현을 사용하여 IComparer 지정된 값과 요소를 array 비교합니다. 정의 array 한 정렬 순서 comparer에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

null경우 comparer 요소 자체 또는 지정된 값으로 제공된 구현을 사용하여 IComparable 비교가 수행됩니다. array 구현에서 정의 IComparable 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

참고

인터페이스를 null value 구현 IComparable 하지 않는 경우 comparer 검색이 시작되기 전에 해당 요소가 array 테스트 IComparable 되지 않습니다. 검색에서 구현 IComparable하지 않는 요소를 발견하면 예외가 throw됩니다.

중복 요소가 허용됩니다. Array 두 개 이상의 요소가 같은 value경우 메서드는 발생 중 하나의 인덱스만 반환하고 반드시 첫 번째 요소의 인덱스를 반환하지는 않습니다.

null 항상 다른 참조 형식과 비교할 수 있습니다. 따라서 비교를 사용하는 null IComparable경우 예외가 생성되지 않습니다.

참고

테스트된 value 모든 요소에 대해 적절한 IComparable 구현에 전달됩니다null(있는 경우)value. 즉, 구현은 IComparable 지정된 요소와 비교하는 방법을 결정합니다 null.

이 메서드는 O(로그 n) 작업 n 입니다 length.

추가 정보

적용 대상

BinarySearch<T>(T[], T)

Array의 각 요소 및 지정한 개체에서 구현되는 IComparable<T> 제네릭 인터페이스를 사용하여 1차원으로 정렬된 전체 배열에서 특정 요소를 검색합니다.

public:
generic <typename T>
 static int BinarySearch(cli::array <T> ^ array, T value);
public static int BinarySearch<T> (T[] array, T value);
static member BinarySearch : 'T[] * 'T -> int
Public Shared Function BinarySearch(Of T) (array As T(), value As T) As Integer

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

검색할 정렬된 1차원 Array(0부터 시작)입니다.

value
T

검색할 개체입니다.

반환

Int32

value가 있는 경우 지정된 array에 있는 지정된 value의 인덱스이고, 그렇지 않으면 음수입니다. value가 없고 valuearray에 있는 하나 이상의 요소보다 작은 경우 value보다 큰 첫째 요소 인덱스의 비트 보수인 음수가 반환됩니다. value가 없고 valuearray에 있는 모든 요소보다 큰 경우 마지막 요소에 1을 더한 인덱스의 비트 보수인 음수가 반환됩니다. 이 메서드가 정렬되지 않은 array를 사용하여 호출되면 valuearray에 있더라도 반환 값이 올바르지 않고 음수가 반환될 수 있습니다.

예외

array이(가) null인 경우

TIComparable<T> 제네릭 인터페이스를 구현하지 않습니다.

예제

다음 코드 예제에서는 제네릭 메서드 오버로드 및 제네릭 메서드 오버로드를 BinarySearch<T>(T[], T) 보여 Sort<T>(T[]) 줍니다. 문자열 배열은 특정 순서 없이 만들어집니다.

배열이 표시되고 정렬되고 다시 표시됩니다. 메서드를 사용 BinarySearch 하려면 배열을 정렬해야 합니다.

참고

Visual Basic, F#, C#, BinarySearch C++가 첫 번째 인수의 형식에서 제네릭 형식 매개 변수의 형식을 유추하기 때문에 제네릭 메서드 및 제네릭 메서드에 대한 호출 Sort 은 해당 비제네릭 메서드에 대한 호출과 다르지 않습니다. Ildasm.exe(IL 디스어셈블러)를 사용하여 MSIL(Microsoft 중간 언어)을 검사하는 경우 제네릭 메서드가 호출되고 있음을 확인할 수 있습니다.

BinarySearch<T>(T[], T) 그런 다음 제네릭 메서드 오버로드는 배열에 없는 문자열과 문자열을 검색하는 데 사용됩니다. 메서드의 배열 및 반환 값은 제네릭 메서드(showWhereF# 예제의 BinarySearch 함수)로 전달 ShowWhere 됩니다. 이 메서드는 문자열이 발견되면 인덱스 값을 표시하고, 그렇지 않으면 검색 문자열이 배열에 있는 경우 사이에 있는 요소가 표시됩니다. 문자열이 배열에 없는 경우 인덱스는 음수이므로 ShowWhere 메서드는 비트 보수(C#의 ~ 연산자 및 Visual C++, F#의 ~~~ 연산자, XorVisual Basic -1)를 사용하여 검색 문자열보다 큰 목록의 첫 번째 요소의 인덱스(인덱스)를 가져옵니다.

using namespace System;
using namespace System::Collections::Generic;

generic<typename T> void ShowWhere(array<T>^ arr, int index)
{
    if (index<0)
    {
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        //
        index = ~index;

        Console::Write("Not found. Sorts between: ");

        if (index == 0)
            Console::Write("beginning of array and ");
        else
            Console::Write("{0} and ", arr[index-1]);

        if (index == arr->Length)
            Console::WriteLine("end of array.");
        else
            Console::WriteLine("{0}.", arr[index]);
    }
    else
    {
        Console::WriteLine("Found at index {0}.", index);
    }
};

void main()
{
    array<String^>^ dinosaurs = {"Pachycephalosaurus", 
                                 "Amargasaurus", 
                                 "Tyrannosaurus", 
                                 "Mamenchisaurus", 
                                 "Deinonychus", 
                                 "Edmontosaurus"};

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nSort");
    Array::Sort(dinosaurs);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nBinarySearch for 'Coelophysis':");
    int index = Array::BinarySearch(dinosaurs, "Coelophysis");
    ShowWhere(dinosaurs, index);

    Console::WriteLine("\nBinarySearch for 'Tyrannosaurus':");
    index = Array::BinarySearch(dinosaurs, "Tyrannosaurus");
    ShowWhere(dinosaurs, index);
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Amargasaurus and Deinonychus.

BinarySearch for 'Tyrannosaurus':
Found at index 5.
 */
using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {"Pachycephalosaurus",
                              "Amargasaurus",
                              "Tyrannosaurus",
                              "Mamenchisaurus",
                              "Deinonychus",
                              "Edmontosaurus"};

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nSort");
        Array.Sort(dinosaurs);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nBinarySearch for 'Coelophysis':");
        int index = Array.BinarySearch(dinosaurs, "Coelophysis");
        ShowWhere(dinosaurs, index);

        Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus");
        ShowWhere(dinosaurs, index);
    }

    private static void ShowWhere<T>(T[] array, int index)
    {
        if (index<0)
        {
            // If the index is negative, it represents the bitwise
            // complement of the next larger element in the array.
            //
            index = ~index;

            Console.Write("Not found. Sorts between: ");

            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index-1]);

            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Amargasaurus and Deinonychus.

BinarySearch for 'Tyrannosaurus':
Found at index 5.
 */
open System

let showWhere (array: 'a []) index =
    if index < 0 then
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        let index = ~~~index

        printf "Not found. Sorts between: "

        if index = 0 then
            printf "beginning of array and "
        else
            printf $"{array[index - 1]} and "

        if index = array.Length then
            printfn "end of array."
        else
            printfn $"{array[index]}."
    else
        printfn $"Found at index {index}."

let dinosaurs =
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Tyrannosaurus"
       "Mamenchisaurus"
       "Deinonychus"
       "Edmontosaurus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nSort"
Array.Sort dinosaurs

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nBinarySearch for 'Coelophysis':"
let index = Array.BinarySearch(dinosaurs, "Coelophysis")
showWhere dinosaurs index

printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus")
|> showWhere dinosaurs


// This code example produces the following output:
//
//     Pachycephalosaurus
//     Amargasaurus
//     Tyrannosaurus
//     Mamenchisaurus
//     Deinonychus
//     Edmontosaurus
//
//     Sort
//
//     Amargasaurus
//     Deinonychus
//     Edmontosaurus
//     Mamenchisaurus
//     Pachycephalosaurus
//     Tyrannosaurus
//
//     BinarySearch for 'Coelophysis':
//     Not found. Sorts between: Amargasaurus and Deinonychus.
//
//     BinarySearch for 'Tyrannosaurus':
//     Found at index 5.
Imports System.Collections.Generic

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs() As String = { _
            "Pachycephalosaurus", _
            "Amargasaurus", _
            "Tyrannosaurus", _
            "Mamenchisaurus", _
            "Deinonychus", _
            "Edmontosaurus"  }

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & "Sort")
        Array.Sort(dinosaurs)

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "BinarySearch for 'Coelophysis':")
        Dim index As Integer = _
            Array.BinarySearch(dinosaurs, "Coelophysis")
        ShowWhere(dinosaurs, index)

        Console.WriteLine(vbLf & _
            "BinarySearch for 'Tyrannosaurus':")
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus")
        ShowWhere(dinosaurs, index)

    End Sub

    Private Shared Sub ShowWhere(Of T) _
        (ByVal array() As T, ByVal index As Integer) 

        If index < 0 Then
            ' If the index is negative, it represents the bitwise
            ' complement of the next larger element in the array.
            '
            index = index Xor -1

            Console.Write("Not found. Sorts between: ")

            If index = 0 Then
                Console.Write("beginning of array and ")
            Else
                Console.Write("{0} and ", array(index - 1))
            End If 

            If index = array.Length Then
                Console.WriteLine("end of array.")
            Else
                Console.WriteLine("{0}.", array(index))
            End If 
        Else
            Console.WriteLine("Found at index {0}.", index)
        End If

    End Sub

End Class

' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Tyrannosaurus
'Mamenchisaurus
'Deinonychus
'Edmontosaurus
'
'Sort
'
'Amargasaurus
'Deinonychus
'Edmontosaurus
'Mamenchisaurus
'Pachycephalosaurus
'Tyrannosaurus
'
'BinarySearch for 'Coelophysis':
'Not found. Sorts between: Amargasaurus and Deinonychus.
'
'BinarySearch for 'Tyrannosaurus':
'Found at index 5.

설명

이 메서드는 음수 인덱스를 포함하는 배열 검색을 지원하지 않습니다. array 이 메서드를 호출하기 전에 정렬해야 합니다.

array 지정된 값을 포함하지 않으면 메서드는 음수 정수를 반환합니다. 비트 보수 연산자(C#의 Not 경우~ Visual Basic)를 음수 결과에 적용하여 인덱스 생성할 수 있습니다. 이 인덱스가 배열의 크기와 같으면 배열보다 value 큰 요소가 없습니다. 그렇지 않으면 첫 번째 요소의 인덱스가 .보다 value큰 인덱스입니다.

T 는 비교에 IComparable<T> 사용되는 제네릭 인터페이스를 구현해야 합니다. array 구현에서 정의 IComparable<T> 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

중복 요소가 허용됩니다. Array 두 개 이상의 요소가 같은 value경우 메서드는 발생 중 하나의 인덱스만 반환하며 반드시 첫 번째 요소가 아닌 인덱스를 반환합니다.

null 항상 다른 참조 형식과 비교할 수 있습니다. 따라서 비교는 예외를 null 생성하지 않습니다.

참고

테스트된 value 모든 요소에 대해 해당 IComparable<T> 구현에 전달됩니다null(있는 경우에도value). 즉, 구현은 IComparable<T> 지정된 요소와 비교하는 방법을 결정합니다 null.

이 메서드는 O(로그n) 연산이며 여기서 nLength array

추가 정보

적용 대상

BinarySearch<T>(T[], T, IComparer<T>)

지정한 IComparer<T> 제네릭 인터페이스를 사용하여 1차원으로 정렬된 전체 배열에서 값을 검색합니다.

public:
generic <typename T>
 static int BinarySearch(cli::array <T> ^ array, T value, System::Collections::Generic::IComparer<T> ^ comparer);
public static int BinarySearch<T> (T[] array, T value, System.Collections.Generic.IComparer<T> comparer);
public static int BinarySearch<T> (T[] array, T value, System.Collections.Generic.IComparer<T>? comparer);
static member BinarySearch : 'T[] * 'T * System.Collections.Generic.IComparer<'T> -> int
Public Shared Function BinarySearch(Of T) (array As T(), value As T, comparer As IComparer(Of T)) As Integer

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

검색할 정렬된 1차원 Array(0부터 시작)입니다.

value
T

검색할 개체입니다.

comparer
IComparer<T>

요소를 비교할 때 사용하는 IComparer<T> 구현입니다.

또는

각 요소의 IComparable<T> 구현을 사용할 null입니다.

반환

Int32

value가 있는 경우 지정된 array에 있는 지정된 value의 인덱스이고, 그렇지 않으면 음수입니다. value가 없고 valuearray에 있는 하나 이상의 요소보다 작은 경우 value보다 큰 첫째 요소 인덱스의 비트 보수인 음수가 반환됩니다. value가 없고 valuearray에 있는 모든 요소보다 큰 경우 마지막 요소에 1을 더한 인덱스의 비트 보수인 음수가 반환됩니다. 이 메서드가 정렬되지 않은 array를 사용하여 호출되면 valuearray에 있더라도 반환 값이 올바르지 않고 음수가 반환될 수 있습니다.

예외

array이(가) null인 경우

comparernull이고 valuearray의 요소와 호환되지 않는 형식입니다.

comparernull이고 TIComparable<T> 제네릭 인터페이스를 구현하지 않습니다.

예제

다음 예제에서는 제네릭 메서드 오버로드 및 제네릭 메서드 오버로드를 BinarySearch<T>(T[], T, IComparer<T>) 보여 Sort<T>(T[], IComparer<T>) 줍니다.

코드 예제에서는 (IComparer(Of String)Visual BasicIComparer<String^>, Visual C++) 제네릭 인터페이스를 구현 IComparer<string> 하는 문자열ReverseCompare에 대한 대체 비교자를 정의합니다. 비교자는 메서드를 CompareTo(String) 호출하여 문자열이 낮음에서 높음으로 정렬되는 대신 높음에서 낮은 값으로 정렬되도록 비교값의 순서를 반전합니다.

배열이 표시되고 정렬되고 다시 표시됩니다. 메서드를 사용 BinarySearch 하려면 배열을 정렬해야 합니다.

참고

Visual Basic, C#, BinarySearch<T>(T[], T, IComparer<T>) C++가 첫 번째 인수의 형식에서 제네릭 형식 매개 변수의 형식을 유추하기 때문에 제네릭 메서드 및 제네릭 메서드에 대한 호출 Sort<T>(T[], IComparer<T>) 은 해당 비제네릭 메서드에 대한 호출과 다르지 않습니다. Ildasm.exe(IL 디스어셈블러)를 사용하여 MSIL(Microsoft 중간 언어)을 검사하는 경우 제네릭 메서드가 호출되고 있음을 확인할 수 있습니다.

BinarySearch<T>(T[], T, IComparer<T>) 그런 다음 제네릭 메서드 오버로드는 배열에 없는 문자열과 문자열을 검색하는 데 사용됩니다. 메서드의 배열 및 반환 값은 제네릭 메서드(showWhereF# 예제의 BinarySearch<T>(T[], T, IComparer<T>) 함수)로 전달 ShowWhere 됩니다. 이 메서드는 문자열이 발견되면 인덱스 값을 표시하고, 그렇지 않으면 검색 문자열이 배열에 있는 경우 사이에 있는 요소가 표시됩니다. 문자열이 n 배열이 아니면 인덱스가 음수이므로 ShowWhere 메서드는 비트 보수(C#의 ~ 연산자 및 Visual C++, F#의 ~~~ 연산자, Xor Visual Basic -1)를 사용하여 검색 문자열보다 큰 목록의 첫 번째 요소의 인덱스 가져오기를 수행합니다.

using namespace System;
using namespace System::Collections::Generic;

public ref class ReverseComparer: IComparer<String^>
{
public:
    virtual int Compare(String^ x, String^ y)
    {
        // Compare y and x in reverse order.
        return y->CompareTo(x);
    }
};

generic<typename T> void ShowWhere(array<T>^ arr, int index)
{
    if (index<0)
    {
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        //
        index = ~index;

        Console::Write("Not found. Sorts between: ");

        if (index == 0)
            Console::Write("beginning of array and ");
        else
            Console::Write("{0} and ", arr[index-1]);

        if (index == arr->Length)
            Console::WriteLine("end of array.");
        else
            Console::WriteLine("{0}.", arr[index]);
    }
    else
    {
        Console::WriteLine("Found at index {0}.", index);
    }
};

void main()
{
    array<String^>^ dinosaurs = {"Pachycephalosaurus", 
                                 "Amargasaurus", 
                                 "Tyrannosaurus", 
                                 "Mamenchisaurus", 
                                 "Deinonychus", 
                                 "Edmontosaurus"};

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

    Console::WriteLine("\nSort");
    Array::Sort(dinosaurs, rc);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nBinarySearch for 'Coelophysis':");
    int index = Array::BinarySearch(dinosaurs, "Coelophysis", rc);
    ShowWhere(dinosaurs, index);

    Console::WriteLine("\nBinarySearch for 'Tyrannosaurus':");
    index = Array::BinarySearch(dinosaurs, "Tyrannosaurus", rc);
    ShowWhere(dinosaurs, index);
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Deinonychus and Amargasaurus.

BinarySearch for 'Tyrannosaurus':
Found at index 0.
 */
using System;
using System.Collections.Generic;

public class ReverseComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        // Compare y and x in reverse order.
        return y.CompareTo(x);
    }
}

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {"Pachycephalosaurus",
                              "Amargasaurus",
                              "Tyrannosaurus",
                              "Mamenchisaurus",
                              "Deinonychus",
                              "Edmontosaurus"};

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort");
        Array.Sort(dinosaurs, rc);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nBinarySearch for 'Coelophysis':");
        int index = Array.BinarySearch(dinosaurs, "Coelophysis", rc);
        ShowWhere(dinosaurs, index);

        Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc);
        ShowWhere(dinosaurs, index);
    }

    private static void ShowWhere<T>(T[] array, int index)
    {
        if (index<0)
        {
            // If the index is negative, it represents the bitwise
            // complement of the next larger element in the array.
            //
            index = ~index;

            Console.Write("Not found. Sorts between: ");

            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index-1]);

            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Deinonychus and Amargasaurus.

BinarySearch for 'Tyrannosaurus':
Found at index 0.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            // Compare y and x in reverse order.
            y.CompareTo x

let showWhere (array: 'a []) index =
    if index < 0 then
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        let index = ~~~index

        printf "Not found. Sorts between: "

        if index = 0 then
            printf "beginning of array and "
        else
            printf $"{array[index - 1]} and "

        if index = array.Length then
            printfn "end of array."
        else
            printfn $"{array[index]}."
    else
        printfn $"Found at index {index}."

let dinosaurs =
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Tyrannosaurus"
       "Mamenchisaurus"
       "Deinonychus"
       "Edmontosaurus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

let rc = ReverseComparer()

printfn "\nSort"
Array.Sort(dinosaurs, rc)

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nBinarySearch for 'Coelophysis':"
Array.BinarySearch(dinosaurs, "Coelophysis", rc)
|> showWhere dinosaurs

printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
|> showWhere dinosaurs


// This code example produces the following output:
//     Pachycephalosaurus
//     Amargasaurus
//     Tyrannosaurus
//     Mamenchisaurus
//     Deinonychus
//     Edmontosaurus
//
//     Sort
//
//     Tyrannosaurus
//     Pachycephalosaurus
//     Mamenchisaurus
//     Edmontosaurus
//     Deinonychus
//     Amargasaurus
//
//     BinarySearch for 'Coelophysis':
//     Not found. Sorts between: Deinonychus and Amargasaurus.
//
//     BinarySearch for 'Tyrannosaurus':
//     Found at index 0.
Imports System.Collections.Generic

Public Class ReverseComparer
    Implements IComparer(Of String)

    Public Function Compare(ByVal x As String, _
        ByVal y As String) As Integer _
        Implements IComparer(Of String).Compare

        ' Compare y and x in reverse order.
        Return y.CompareTo(x)

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs() As String = { _
            "Pachycephalosaurus", _
            "Amargasaurus", _
            "Tyrannosaurus", _
            "Mamenchisaurus", _
            "Deinonychus", _
            "Edmontosaurus"  }

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Dim rc As New ReverseComparer()

        Console.WriteLine(vbLf & "Sort")
        Array.Sort(dinosaurs, rc)

        Console.WriteLine()
        For Each dinosaur As String In dinosaurs
            Console.WriteLine(dinosaur)
        Next

        Console.WriteLine(vbLf & _
            "BinarySearch for 'Coelophysis':")
        Dim index As Integer = _
            Array.BinarySearch(dinosaurs, "Coelophysis", rc)
        ShowWhere(dinosaurs, index)

        Console.WriteLine(vbLf & _
            "BinarySearch for 'Tyrannosaurus':")
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
        ShowWhere(dinosaurs, index)

    End Sub

    Private Shared Sub ShowWhere(Of T) _
        (ByVal array() As T, ByVal index As Integer) 

        If index < 0 Then
            ' If the index is negative, it represents the bitwise
            ' complement of the next larger element in the array.
            '
            index = index Xor -1

            Console.Write("Not found. Sorts between: ")

            If index = 0 Then
                Console.Write("beginning of array and ")
            Else
                Console.Write("{0} and ", array(index - 1))
            End If 

            If index = array.Length Then
                Console.WriteLine("end of array.")
            Else
                Console.WriteLine("{0}.", array(index))
            End If 
        Else
            Console.WriteLine("Found at index {0}.", index)
        End If

    End Sub

End Class

' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Tyrannosaurus
'Mamenchisaurus
'Deinonychus
'Edmontosaurus
'
'Sort
'
'Tyrannosaurus
'Pachycephalosaurus
'Mamenchisaurus
'Edmontosaurus
'Deinonychus
'Amargasaurus
'
'BinarySearch for 'Coelophysis':
'Not found. Sorts between: Deinonychus and Amargasaurus.
'
'BinarySearch for 'Tyrannosaurus':
'Found at index 0.

설명

이 메서드는 음수 인덱스를 포함하는 배열 검색을 지원하지 않습니다. array 이 메서드를 호출하기 전에 정렬해야 합니다.

지정된 값이 Array 없으면 메서드는 음수 정수 값을 반환합니다. 비트 보수 연산자(C#의 Not 경우~ Visual Basic)를 음수 결과에 적용하여 인덱스 생성할 수 있습니다. 이 인덱스가 배열의 크기와 같으면 배열보다 value 큰 요소가 없습니다. 그렇지 않으면 첫 번째 요소의 인덱스가 .보다 value큰 인덱스입니다.

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

그렇지 않은 null경우 comparer 지정된 제네릭 인터페이스 구현을 사용하여 지정된 값과 IComparer<T> 요소를 array 비교합니다. 요소가 array 정의된 comparer정렬 순서에 따라 증가 값으로 이미 정렬되어야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

이 경우 comparer 비교는 에서 제공하는 제네릭 인터페이스 구현을 IComparable<T> 사용하여 수행됩니다T.null array 구현에서 정의 IComparable<T> 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

참고

value null 제네릭 인터페이스를 IComparable<T> 구현하지 않고 있는 경우 comparer 검색이 array 시작되기 전에 요소가 테스트 IComparable<T> 되지 않습니다. 검색에서 구현 IComparable<T>하지 않는 요소가 발견되면 예외가 throw됩니다.

중복 요소가 허용됩니다. Array 두 개 이상의 요소가 같은 value경우 메서드는 발생 중 하나의 인덱스만 반환하며 반드시 첫 번째 요소가 아닌 인덱스를 반환합니다.

null 항상 다른 참조 형식과 비교할 수 있습니다. 따라서 비교는 예외를 null 생성하지 않습니다.

참고

테스트된 value 모든 요소에 대해 해당 IComparable<T> 구현에 전달됩니다null(있는 경우에도value). 즉, 구현은 IComparable<T> 지정된 요소와 비교하는 방법을 결정합니다 null.

이 메서드는 O(로그n) 연산이며 여기서 nLength array

추가 정보

적용 대상

BinarySearch<T>(T[], Int32, Int32, T)

Array의 각 요소 및 지정한 값에서 구현되는 IComparable<T> 제네릭 인터페이스를 사용하여 1차원으로 정렬된 배열의 요소 범위에서 값을 검색합니다.

public:
generic <typename T>
 static int BinarySearch(cli::array <T> ^ array, int index, int length, T value);
public static int BinarySearch<T> (T[] array, int index, int length, T value);
static member BinarySearch : 'T[] * int * int * 'T -> int
Public Shared Function BinarySearch(Of T) (array As T(), index As Integer, length As Integer, value As T) As Integer

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

검색할 정렬된 1차원 Array(0부터 시작)입니다.

index
Int32

검색할 범위의 시작 인덱스입니다.

length
Int32

검색할 범위의 길이입니다.

value
T

검색할 개체입니다.

반환

Int32

value가 있는 경우 지정된 array에 있는 지정된 value의 인덱스이고, 그렇지 않으면 음수입니다. value가 없고 valuearray에 있는 하나 이상의 요소보다 작은 경우 value보다 큰 첫째 요소 인덱스의 비트 보수인 음수가 반환됩니다. value가 없고 valuearray에 있는 모든 요소보다 큰 경우 마지막 요소에 1을 더한 인덱스의 비트 보수인 음수가 반환됩니다. 이 메서드가 정렬되지 않은 array를 사용하여 호출되면 valuearray에 있더라도 반환 값이 올바르지 않고 음수가 반환될 수 있습니다.

예외

array이(가) null인 경우

indexarray의 하한값보다 작습니다.

또는

length가 0보다 작은 경우

indexlengtharray의 올바른 범위를 지정하지 않습니다.

또는

value의 형식이 array의 요소와 호환되지 않는 형식입니다.

TIComparable<T> 제네릭 인터페이스를 구현하지 않습니다.

설명

이 메서드는 음수 인덱스를 포함하는 배열 검색을 지원하지 않습니다. array 이 메서드를 호출하기 전에 정렬해야 합니다.

배열에 지정된 값이 없으면 메서드는 음수 정수가 반환됩니다. 비트 보수 연산자(C#의 Not 경우~ Visual Basic)를 음수 결과에 적용하여 인덱스 생성할 수 있습니다. 이 인덱스가 배열의 크기와 같으면 배열보다 value 큰 요소가 없습니다. 그렇지 않으면 첫 번째 요소의 인덱스가 .보다 value큰 인덱스입니다.

T 는 비교에 IComparable<T> 사용되는 제네릭 인터페이스를 구현해야 합니다. array 구현에서 정의 IComparable<T> 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

중복 요소가 허용됩니다. Array 두 개 이상의 요소가 같은 value경우 메서드는 발생 중 하나의 인덱스만 반환하며 반드시 첫 번째 요소가 아닌 인덱스를 반환합니다.

null 항상 다른 참조 형식과 비교할 수 있습니다. 따라서 비교는 예외를 null 생성하지 않습니다.

참고

테스트된 value 모든 요소에 대해 해당 IComparable<T> 구현에 전달됩니다null(있는 경우에도value). 즉, 구현은 IComparable<T> 지정된 요소와 비교하는 방법을 결정합니다 null.

이 메서드는 O(로그 n) 작업입니다. 여기서는 다음과 n 같습니다 length.

추가 정보

적용 대상

BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)

지정한 IComparer<T> 제네릭 인터페이스를 사용하여 1차원으로 정렬된 배열의 요소 범위에서 값을 검색합니다.

public:
generic <typename T>
 static int BinarySearch(cli::array <T> ^ array, int index, int length, T value, System::Collections::Generic::IComparer<T> ^ comparer);
public static int BinarySearch<T> (T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer);
public static int BinarySearch<T> (T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T>? comparer);
static member BinarySearch : 'T[] * int * int * 'T * System.Collections.Generic.IComparer<'T> -> int
Public Shared Function BinarySearch(Of T) (array As T(), index As Integer, length As Integer, value As T, comparer As IComparer(Of T)) As Integer

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

검색할 정렬된 1차원 Array(0부터 시작)입니다.

index
Int32

검색할 범위의 시작 인덱스입니다.

length
Int32

검색할 범위의 길이입니다.

value
T

검색할 개체입니다.

comparer
IComparer<T>

요소를 비교할 때 사용하는 IComparer<T> 구현입니다.

또는

각 요소의 IComparable<T> 구현을 사용할 null입니다.

반환

Int32

value가 있는 경우 지정된 array에 있는 지정된 value의 인덱스이고, 그렇지 않으면 음수입니다. value가 없고 valuearray에 있는 하나 이상의 요소보다 작은 경우 value보다 큰 첫째 요소 인덱스의 비트 보수인 음수가 반환됩니다. value가 없고 valuearray에 있는 모든 요소보다 큰 경우 마지막 요소에 1을 더한 인덱스의 비트 보수인 음수가 반환됩니다. 이 메서드가 정렬되지 않은 array를 사용하여 호출되면 valuearray에 있더라도 반환 값이 올바르지 않고 음수가 반환될 수 있습니다.

예외

array이(가) null인 경우

indexarray의 하한값보다 작습니다.

또는

length가 0보다 작은 경우

indexlengtharray의 올바른 범위를 지정하지 않습니다.

또는

comparernull이고 valuearray의 요소와 호환되지 않는 형식입니다.

comparernull이고 TIComparable<T> 제네릭 인터페이스를 구현하지 않습니다.

설명

이 메서드는 음수 인덱스를 포함하는 배열 검색을 지원하지 않습니다. array 이 메서드를 호출하기 전에 정렬해야 합니다.

배열에 지정된 값이 없으면 메서드는 음수 정수 값을 반환합니다. 음수 결과에 비트 보수 연산자(C#의 경우~, Not Visual Basic)를 적용하여 인덱스 생성할 수 있습니다. 이 인덱스가 배열의 크기와 같으면 배열보다 value 큰 요소가 없습니다. 그렇지 않으면 첫 번째 요소의 인덱스가 .보다 value큰 경우

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

그렇지 않은 null경우 comparer 지정된 제네릭 인터페이스 구현을 사용하여 지정된 값과 IComparer<T> 요소를 array 비교합니다. 정의 array 한 정렬 순서 comparer에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

null경우 comparer 형식T에 제공된 제네릭 인터페이스 구현을 IComparable<T> 사용하여 비교가 수행됩니다. array 구현에서 정의 IComparable<T> 한 정렬 순서에 따라 값을 늘리기 위해 요소를 이미 정렬해야 합니다. 그렇지 않으면 결과가 올바르지 않을 수 있습니다.

중복 요소가 허용됩니다. Array 두 개 이상의 요소가 같은 value경우 메서드는 발생 중 하나의 인덱스만 반환하고 반드시 첫 번째 요소의 인덱스를 반환하지는 않습니다.

null 항상 다른 참조 형식과 비교할 수 있습니다. 따라서 비교를 사용하는 null IComparable<T>경우 예외가 생성되지 않습니다.

참고

테스트된 value 모든 요소에 대해 적절한 IComparable<T> 구현에 전달됩니다null(있는 경우)value. 즉, 구현은 IComparable<T> 지정된 요소와 비교하는 방법을 결정합니다 null.

이 메서드는 O(로그 n) 작업 n 입니다 length.

추가 정보

적용 대상