Array.Sort 메서드

정의

1차원 배열의 요소를 정렬합니다.

오버로드

Sort(Array, Array, Int32, Int32, IComparer)

지정한 Array 를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 1차원 IComparer개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)의 요소 범위를 정렬합니다.

Sort(Array, Int32, Int32, IComparer)

지정한 Array를 사용하여 1차원 IComparer의 요소 범위에 있는 요소를 정렬합니다.

Sort(Array, Array, Int32, Int32)

각 키의 Array 구현을 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 1차원 IComparable 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)의 요소 범위를 정렬합니다.

Sort(Array, Int32, Int32)

Array 에 있는 각 요소의 IComparable 구현을 사용하여 1차원 Array의 요소 범위에 있는 요소를 정렬합니다.

Sort(Array, Array, IComparer)

지정한 Array 를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 1차원 IComparer개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)를 정렬합니다.

Sort(Array, Array)

Array 구현을 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 1차원 IComparable 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)를 정렬합니다.

Sort(Array)

Array 에 있는 각 요소의 IComparable 구현을 사용하여 1차원 Array전체의 요소를 정렬합니다.

Sort(Array, IComparer)

지정한 Array 를 사용하여 1차원 IComparer의 요소를 정렬합니다.

Sort<T>(T[])

Array 에 있는 각 요소의 IComparable<T> 제네릭 인터페이스 구현을 사용하여 전체 Array의 요소를 정렬합니다.

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

지정한 Array 제네릭 인터페이스를 사용하여 IComparer<T> 의 요소를 정렬합니다.

Sort<T>(T[], Comparison<T>)

지정한 Array 을 사용하여 Comparison<T>의 요소를 정렬합니다.

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

Array 에 있는 각 요소의 IComparable<T> 제네릭 인터페이스 구현을 사용하여 Array의 요소 범위에 있는 요소를 정렬합니다.

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

지정한 Array 제네릭 인터페이스를 사용하여 IComparer<T> 의 요소 범위에 있는 요소를 정렬합니다.

Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)

지정한 Array 제네릭 인터페이스를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 IComparer<T> 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)의 요소 범위를 정렬합니다.

Sort<TKey,TValue>(TKey[], TValue[])

각 키의 Array 제네릭 인터페이스 구현을 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 IComparable<T> 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)를 정렬합니다.

Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)

지정한 Array 제네릭 인터페이스를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 IComparer<T> 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)를 정렬합니다.

Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)

각 키에서 구현하는 Array 제네릭 인터페이스를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 IComparable<T> 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)의 요소 범위를 정렬합니다.

Sort(Array, Array, Int32, Int32, IComparer)

지정한 Array 를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 1차원 IComparer개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)의 요소 범위를 정렬합니다.

public:
 static void Sort(Array ^ keys, Array ^ items, int index, int length, System::Collections::IComparer ^ comparer);
public static void Sort (Array keys, Array items, int index, int length, System.Collections.IComparer comparer);
public static void Sort (Array keys, Array? items, int index, int length, System.Collections.IComparer? comparer);
static member Sort : Array * Array * int * int * System.Collections.IComparer -> unit
Public Shared Sub Sort (keys As Array, items As Array, index As Integer, length As Integer, comparer As IComparer)

매개 변수

keys
Array

정렬할 키를 포함하는 1차원 Array 입니다.

items
Array

keysArray의 각 키에 해당하는 항목을 포함하는 1차원 Array입니다.

또는

keysArray만을 정렬하는 null입니다.

index
Int32

정렬할 범위의 시작 인덱스입니다.

length
Int32

정렬할 범위에 있는 요소 수입니다.

comparer
IComparer

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

또는

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

예외

keys이(가) null인 경우

keysArray가 다차원 배열입니다.

또는

itemsArray가 다차원 배열입니다.

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

또는

length가 0보다 작은 경우

itemsnull이 아니고 keys 의 하한 범위가 items의 하한 범위와 일치하지 않습니다.

또는

itemsnull이 아니고 keys 의 길이가 items의 길이보다 큽니다.

또는

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

또는

itemsnull이 아니고 indexlengthitemsArray의 올바른 범위를 지정하지 않습니다.

또는

comparer의 구현으로 인해 정렬 중에 오류가 발생했습니다. 예를 들어 항목을 자기 자신과 비교할 때 comparer에서 0을 반환하지 않을 수 있습니다.

comparernull이고 keysArray 의 하나 이상의 요소가 IComparable 인터페이스를 구현하지 않습니다.

예제

다음 코드 예제에서는 첫 번째 배열에 키가 포함되고 두 번째 배열에 값이 포함된 두 개의 연결된 배열을 정렬하는 방법을 보여 줍니다. 정렬은 기본 비교자와 정렬 순서를 반대로 하는 사용자 지정 비교자를 사용하여 수행됩니다. 결과는 현재 CultureInfo에 따라 달라질 수 있습니다.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

   // Calls CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
   }
};

void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
   for ( int i = 0; i < myKeys->Length; i++ )
   {
      Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
   }
   Console::WriteLine();
}

int main()
{
   // Creates and initializes a new Array and a new custom comparer.
   array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
   array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
   IComparer^ myComparer = gcnew myReverserClass;

   // Displays the values of the Array.
   Console::WriteLine( "The Array initially contains the following values:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts a section of the Array using the default comparer.
   Array::Sort( myKeys, myValues, 1, 3 );
   Console::WriteLine( "After sorting a section of the Array using the default comparer:" );

   // Sorts a section of the Array using the reverse case-insensitive comparer.
   Array::Sort( myKeys, myValues, 1, 3, myComparer );
   Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts the entire Array using the default comparer.
   Array::Sort( myKeys, myValues );
   Console::WriteLine( "After sorting the entire Array using the default comparer:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts the entire Array using the reverse case-insensitive comparer.
   Array::Sort( myKeys, myValues, myComparer );
   Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
   PrintKeysAndValues( myKeys, myValues );
}

/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
using System;
using System.Collections;

public class SamplesArray  {

   public class myReverserClass : IComparer  {

      // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }
   }

   public static void Main()  {

      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();

      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts a section of the Array using the reverse case-insensitive comparer.
      Array.Sort( myKeys, myValues, 1, 3, myComparer );
      Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts the entire Array using the default comparer.
      Array.Sort( myKeys, myValues );
      Console.WriteLine( "After sorting the entire Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts the entire Array using the reverse case-insensitive comparer.
      Array.Sort( myKeys, myValues, myComparer );
      Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
      PrintKeysAndValues( myKeys, myValues );
   }

   public static void PrintKeysAndValues( String[] myKeys, String[] myValues )  {
      for ( int i = 0; i < myKeys.Length; i++ )  {
         Console.WriteLine( "   {0,-10}: {1}", myKeys[i], myValues[i] );
      }
      Console.WriteLine();
   }
}


/*
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
open System
open System.Collections

type MyReverserClass() = 
    interface IComparer with
        member _.Compare(x, y) =
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let printKeysAndValues (myKeys: string []) (myValues: string []) =
    for i = 0 to myKeys.Length - 1 do
        printfn $"   {myKeys[i],-10}: {myValues[i]}"
    printfn ""

// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()

// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues 

// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:" 
printKeysAndValues myKeys myValues

// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues


// This code produces the following output.
//     The Array initially contains the following values:
//        red       : strawberries
//        GREEN     : PEARS
//        YELLOW    : LIMES
//        BLUE      : BERRIES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting a section of the Array using the default comparer:
//        red       : strawberries
//        BLUE      : BERRIES
//        GREEN     : PEARS
//        YELLOW    : LIMES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting a section of the Array using the reverse case-insensitive comparer:
//        red       : strawberries
//        YELLOW    : LIMES
//        GREEN     : PEARS
//        BLUE      : BERRIES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting the entire Array using the default comparer:
//        black     : olives
//        BLUE      : BERRIES
//        GREEN     : PEARS
//        orange    : cantaloupe
//        purple    : grapes
//        red       : strawberries
//        YELLOW    : LIMES
//     
//     After sorting the entire Array using the reverse case-insensitive comparer:
//        YELLOW    : LIMES
//        red       : strawberries
//        purple    : grapes
//        orange    : cantaloupe
//        GREEN     : PEARS
//        BLUE      : BERRIES
//        black     : olives
Imports System.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

      ' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      Function Compare(x As [Object], y As [Object]) As Integer _
         Implements IComparer.Compare
         Return New CaseInsensitiveComparer().Compare(y, x)
      End Function 'IComparer.Compare

   End Class


   Public Shared Sub Main()

      ' Creates and initializes a new Array and a new custom comparer.
      Dim myKeys As [String]() =  {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
      Dim myValues As [String]() =  {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
      Dim myComparer = New myReverserClass()

      ' Displays the values of the Array.
      Console.WriteLine("The Array initially contains the following values:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts a section of the Array using the default comparer.
      Array.Sort(myKeys, myValues, 1, 3)
      Console.WriteLine("After sorting a section of the Array using the default comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts a section of the Array using the reverse case-insensitive comparer.
      Array.Sort(myKeys, myValues, 1, 3, myComparer)
      Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts the entire Array using the default comparer.
      Array.Sort(myKeys, myValues)
      Console.WriteLine("After sorting the entire Array using the default comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts the entire Array using the reverse case-insensitive comparer.
      Array.Sort(myKeys, myValues, myComparer)
      Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
      PrintKeysAndValues(myKeys, myValues)

   End Sub


   Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])

      Dim i As Integer
      For i = 0 To myKeys.Length - 1
         Console.WriteLine("   {0,-10}: {1}", myKeys(i), myValues(i))
      Next i
      Console.WriteLine()

   End Sub

End Class


'This code produces the following output.
'
'The Array initially contains the following values:
'   red       : strawberries
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the default comparer:
'   red       : strawberries
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
'   red       : strawberries
'   YELLOW    : LIMES
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting the entire Array using the default comparer:
'   black     : olives
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   orange    : cantaloupe
'   purple    : grapes
'   red       : strawberries
'   YELLOW    : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
'   YELLOW    : LIMES
'   red       : strawberries
'   purple    : grapes
'   orange    : cantaloupe
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   black     : olives

설명

keysArray 각 키에는 에 해당 항목이 itemsArray있습니다. 정렬하는 동안 키의 위치가 변경되면 의 해당 항목 itemsArray 의 위치도 비슷하게 변경됩니다. 따라서 는 itemsArray 에서 해당 키의 정렬에 따라 정렬됩니다 keysArray.

가 이nullcomparer 의 지정된 요소 범위 내의 각 키는 keysArray 다른 모든 키와 비교할 수 있도록 인터페이스를 구현 IComparable 해야 합니다.

키보다 많은 항목이 있는 경우 정렬할 수 있지만 해당 키가 없는 항목은 정렬되지 않습니다. 항목보다 더 많은 키가 있는 경우 정렬할 수 없습니다. 이렇게 하면 가 ArgumentExceptionthrow됩니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

.NET에는 다음 표에 나열된 미리 정의된 IComparer 구현이 포함되어 있습니다.

구현 설명
System.Collections.CaseInsensitiveComparer 두 개체를 비교하지만 문자열의 대/소문자를 구분하지 않는 비교를 수행합니다.
Comparer.Default 현재 문화권의 정렬 규칙을 사용하여 두 개체를 비교합니다.
Comparer.DefaultInvariant 고정 문화권의 정렬 규칙을 사용하여 두 개체를 비교합니다.
Comparer<T>.Default 형식의 기본 정렬 순서를 사용하여 형식 T 의 두 개체를 비교합니다.

매개 변수에 고유한 IComparer 구현의 instance 제공하여 사용자 지정 비교를 comparer 지원할 수도 있습니다. 이 예제에서는 기본 정렬 순서를 반대로 하고 대/소문자를 구분하지 않는 문자열 비교를 수행하는 사용자 지정 IComparer 구현을 정의하여 이 작업을 수행합니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 입력 배열의 범위인 2 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 구성 알고리즘 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

호출자 참고

.NET Framework 4 이전 버전에서는 빠른 구성 알고리즘만 사용했습니다. Quicksort는 정렬 작업이 예외를 throw하고 호출자에게 예외를 throw IndexOutOfRangeException 하는 일부 상황에서 잘못된 비교자를 식별합니다 ArgumentException . .NET Framework 4.5부터는 삽입 정렬 및 힙소트 알고리즘이 잘못된 비교자를 검색하지 않으므로 이전에 던진 ArgumentException 정렬 작업에서 예외가 throw되지 않을 수 있습니다. 대부분의 경우 16개 요소보다 작거나 같은 배열에 적용됩니다.

추가 정보

적용 대상

Sort(Array, Int32, Int32, IComparer)

지정한 Array를 사용하여 1차원 IComparer의 요소 범위에 있는 요소를 정렬합니다.

public:
 static void Sort(Array ^ array, int index, int length, System::Collections::IComparer ^ comparer);
public static void Sort (Array array, int index, int length, System.Collections.IComparer comparer);
public static void Sort (Array array, int index, int length, System.Collections.IComparer? comparer);
static member Sort : Array * int * int * System.Collections.IComparer -> unit
Public Shared Sub Sort (array As Array, index As Integer, length As Integer, comparer As IComparer)

매개 변수

array
Array

정렬할 1차원 Array 입니다.

index
Int32

정렬할 범위의 시작 인덱스입니다.

length
Int32

정렬할 범위에 있는 요소 수입니다.

comparer
IComparer

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

또는

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

예외

array이(가) null인 경우

array가 다차원 배열인 경우

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

또는

length가 0보다 작은 경우

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

또는

comparer의 구현으로 인해 정렬 중에 오류가 발생했습니다. 예를 들어 항목을 자기 자신과 비교할 때 comparer에서 0을 반환하지 않을 수 있습니다.

comparernull이고 array의 요소 중 하나 이상이 IComparable 인터페이스를 구현하지 않는 경우

예제

다음 코드 예제에서는 기본 비교자와 정렬 순서를 반대로 하는 사용자 지정 비교자를 사용하여 의 Array 값을 정렬하는 방법을 보여 줍니다. 결과는 현재 CultureInfo에 따라 달라질 수 있습니다.

using namespace System;
using namespace System::Collections;

public ref class ReverseComparer : IComparer
{
public:
   // Call CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
   }
};

void DisplayValues(array<String^>^ arr)
{
   for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
      Console::WriteLine( "   [{0}] : {1}", i, arr[ i ] );

   Console::WriteLine();
}

int main()
{
   // Create and initialize a new array. and a new custom comparer.
   array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
                             "over","the","lazy","dog" };
   // Instantiate the reverse comparer.
   IComparer^ revComparer = gcnew ReverseComparer();
   
   // Display the values of the Array.
   Console::WriteLine( "The original order of elements in the array:" );
   DisplayValues(words);

   // Sort a section of the array using the default comparer.
   Array::Sort(words, 1, 3);
   Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
   DisplayValues(words);

   // Sort a section of the array using the reverse case-insensitive comparer.
   Array::Sort(words, 1, 3, revComparer);
   Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
   DisplayValues(words);

   // Sort the entire array using the default comparer.
   Array::Sort(words);
   Console::WriteLine( "After sorting the entire array by using the default comparer:");
   DisplayValues(words);

   // Sort the entire array by using the reverse case-insensitive comparer.
   Array::Sort(words, revComparer);
   Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
   DisplayValues(words);
}

/* 
This code produces the following output.

The Array initially contains the following values:
   [0] : The
   [1] : QUICK
   [2] : BROWN
   [3] : FOX
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the default comparer:
   [0] : The
   [1] : BROWN
   [2] : FOX
   [3] : QUICK
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the reverse case-insensitive comparer:
   [0] : The
   [1] : QUICK
   [2] : FOX
   [3] : BROWN
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting the entire Array using the default comparer:
   [0] : BROWN
   [1] : dog
   [2] : FOX
   [3] : jumps
   [4] : lazy
   [5] : over
   [6] : QUICK
   [7] : the
   [8] : The

After sorting the entire Array using the reverse case-insensitive comparer:
   [0] : the
   [1] : The
   [2] : QUICK
   [3] : over
   [4] : lazy
   [5] : jumps
   [6] : FOX
   [7] : dog
   [8] : BROWN

*/
using System;
using System.Collections;

public class ReverseComparer : IComparer
{
   // Call CaseInsensitiveComparer.Compare with the parameters reversed.
   public int Compare(Object x, Object y)
   {
       return (new CaseInsensitiveComparer()).Compare(y, x );
   }
}

public class Example
{
   public static void Main()
   {
      // Create and initialize a new array.
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps",
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();

      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);

      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

      // Sort a section of the array using the reverse case-insensitive comparer.
      Array.Sort(words, 1, 3, revComparer);
      Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
      DisplayValues(words);

      // Sort the entire array using the default comparer.
      Array.Sort(words);
      Console.WriteLine( "After sorting the entire array by using the default comparer:");
      DisplayValues(words);

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }

   public static void DisplayValues(String[] arr)
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
open System
open System.Collections

type ReverseComparer() =
    interface IComparer with
        member _.Compare(x, y) =
            // Call CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let displayValues (arr: string []) = 
    for i = 0 to arr.Length - 1 do
        printfn $"   [{i}] : {arr[i]}"
    printfn ""

// Create and initialize a new array.
let words = 
    [| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
       "over"; "the"; "lazy"; "dog" |]

// Instantiate the reverse comparer.
let revComparer = ReverseComparer()

// Display the values of the array.
printfn "The original order of elements in the array:" 
displayValues words

// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
printfn "After sorting elements 1-3 by using the default comparer:"
displayValues words

// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
printfn "After sorting elements 1-3 by using the reverse case-insensitive comparer:"
displayValues words

// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words

// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words

// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
Imports System.Collections

Public Class ReverseComparer : Implements IComparer
   ' Call CaseInsensitiveComparer.Compare with the parameters reversed.
   Function Compare(x As Object, y As Object) As Integer _
            Implements IComparer.Compare
      Return New CaseInsensitiveComparer().Compare(y, x)
   End Function 
End Class

Public Module Example
   Public Sub Main()
      ' Create and initialize a new array.
      Dim words() As String =  { "The", "QUICK", "BROWN", "FOX", "jumps", 
                                 "over", "the", "lazy", "dog" }
      ' Instantiate a new custom comparer.
      Dim revComparer As New ReverseComparer()

      ' Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" )
      DisplayValues(words)

      ' Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3)
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:")
      DisplayValues(words)

      ' Sort a section of the array using the reverse case-insensitive comparer.
      Array.Sort(words, 1, 3, revComparer)
      Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:")
      DisplayValues(words)

      ' Sort the entire array using the default comparer.
      Array.Sort(words)
      Console.WriteLine( "After sorting the entire array by using the default comparer:")
      DisplayValues(words)

      ' Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer)
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:")
      DisplayValues(words)
   End Sub 

   Public Sub DisplayValues(arr() As String)
      For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
         Console.WriteLine("   [{0}] : {1}", i, arr(i))
      Next 
      Console.WriteLine()
   End Sub 
End Module 
' The example displays the following output:
'    The original order of elements in the array:
'       [0] : The
'       [1] : QUICK
'       [2] : BROWN
'       [3] : FOX
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting elements 1-3 by using the default comparer:
'       [0] : The
'       [1] : BROWN
'       [2] : FOX
'       [3] : QUICK
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting elements 1-3 by using the reverse case-insensitive comparer:
'       [0] : The
'       [1] : QUICK
'       [2] : FOX
'       [3] : BROWN
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting the entire array by using the default comparer:
'       [0] : BROWN
'       [1] : dog
'       [2] : FOX
'       [3] : jumps
'       [4] : lazy
'       [5] : over
'       [6] : QUICK
'       [7] : the
'       [8] : The
'    
'    After sorting the entire array using the reverse case-insensitive comparer:
'       [0] : the
'       [1] : The
'       [2] : QUICK
'       [3] : over
'       [4] : lazy
'       [5] : jumps
'       [6] : FOX
'       [7] : dog
'       [8] : BROWN

설명

가 이nullcomparer 의 지정된 요소 범위 내의 각 요소는 의 다른 모든 요소 arrayarray 와 비교할 수 있도록 인터페이스를 구현 IComparable 해야 합니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

.NET에는 다음 표에 나열된 미리 정의된 IComparer 구현이 포함되어 있습니다.

구현 설명
System.Collections.CaseInsensitiveComparer 두 개체를 비교하지만 문자열의 대/소문자를 구분하지 않는 비교를 수행합니다.
Comparer.Default 현재 문화권의 정렬 규칙을 사용하여 두 개체를 비교합니다.
Comparer.DefaultInvariant 고정 문화권의 정렬 규칙을 사용하여 두 개체를 비교합니다.
Comparer<T>.Default 형식의 기본 정렬 순서를 사용하여 형식 T 의 두 개체를 비교합니다.

매개 변수에 고유한 IComparer 구현의 instance 제공하여 사용자 지정 비교를 comparer 지원할 수도 있습니다. 이 예제에서는 형식 인스턴스의 기본 정렬 순서를 반대로 하고 대/소문자를 구분하지 않는 문자열 비교를 수행하는 클래스를 정의 ReverseComparer 하여 이 작업을 수행합니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 2 * LogN을 초과하는 경우 여기서 N 은 입력 배열의 범위이며 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 정렬 알고리즘을 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

호출자 참고

.NET Framework 4 이전 버전에서는 빠른 구성 알고리즘만 사용했습니다. Quicksort는 정렬 작업이 예외를 throw하고 호출자에게 예외를 throw IndexOutOfRangeException 하는 일부 상황에서 잘못된 비교자를 식별합니다 ArgumentException . .NET Framework 4.5부터는 삽입 정렬 및 힙소트 알고리즘이 잘못된 비교자를 검색하지 않으므로 이전에 던진 ArgumentException 정렬 작업에서 예외가 throw되지 않을 수 있습니다. 대부분의 경우 16개 요소보다 작거나 같은 배열에 적용됩니다.

추가 정보

적용 대상

Sort(Array, Array, Int32, Int32)

각 키의 Array 구현을 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 1차원 IComparable 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)의 요소 범위를 정렬합니다.

public:
 static void Sort(Array ^ keys, Array ^ items, int index, int length);
public static void Sort (Array keys, Array items, int index, int length);
public static void Sort (Array keys, Array? items, int index, int length);
static member Sort : Array * Array * int * int -> unit
Public Shared Sub Sort (keys As Array, items As Array, index As Integer, length As Integer)

매개 변수

keys
Array

정렬할 키를 포함하는 1차원 Array 입니다.

items
Array

keysArray의 각 키에 해당하는 항목을 포함하는 1차원 Array입니다.

또는

keysArray만을 정렬하는 null입니다.

index
Int32

정렬할 범위의 시작 인덱스입니다.

length
Int32

정렬할 범위에 있는 요소 수입니다.

예외

keys이(가) null인 경우

keysArray가 다차원 배열입니다.

또는

itemsArray가 다차원 배열입니다.

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

또는

length가 0보다 작은 경우

itemsnull이 아니고 keys 의 길이가 items의 길이보다 큽니다.

또는

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

또는

itemsnull이 아니고 indexlengthitemsArray의 올바른 범위를 지정하지 않습니다.

keysArray의 요소 중 하나 이상이 IComparable 인터페이스를 구현하지 않습니다.

예제

다음 코드 예제에서는 첫 번째 배열에 키가 포함되고 두 번째 배열에 값이 포함된 두 개의 연결된 배열을 정렬하는 방법을 보여 줍니다. 정렬은 정렬 순서를 반대로 하는 기본 비교자와 사용자 지정 비교자를 사용하여 수행됩니다. 결과는 현재 CultureInfo에 따라 달라질 수 있습니다.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

   // Calls CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
   }
};

void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
   for ( int i = 0; i < myKeys->Length; i++ )
   {
      Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
   }
   Console::WriteLine();
}

int main()
{
   // Creates and initializes a new Array and a new custom comparer.
   array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
   array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
   IComparer^ myComparer = gcnew myReverserClass;

   // Displays the values of the Array.
   Console::WriteLine( "The Array initially contains the following values:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts a section of the Array using the default comparer.
   Array::Sort( myKeys, myValues, 1, 3 );
   Console::WriteLine( "After sorting a section of the Array using the default comparer:" );

   // Sorts a section of the Array using the reverse case-insensitive comparer.
   Array::Sort( myKeys, myValues, 1, 3, myComparer );
   Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts the entire Array using the default comparer.
   Array::Sort( myKeys, myValues );
   Console::WriteLine( "After sorting the entire Array using the default comparer:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts the entire Array using the reverse case-insensitive comparer.
   Array::Sort( myKeys, myValues, myComparer );
   Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
   PrintKeysAndValues( myKeys, myValues );
}

/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
using System;
using System.Collections;

public class SamplesArray  {

   public class myReverserClass : IComparer  {

      // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }
   }

   public static void Main()  {

      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();

      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts a section of the Array using the reverse case-insensitive comparer.
      Array.Sort( myKeys, myValues, 1, 3, myComparer );
      Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts the entire Array using the default comparer.
      Array.Sort( myKeys, myValues );
      Console.WriteLine( "After sorting the entire Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts the entire Array using the reverse case-insensitive comparer.
      Array.Sort( myKeys, myValues, myComparer );
      Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
      PrintKeysAndValues( myKeys, myValues );
   }

   public static void PrintKeysAndValues( String[] myKeys, String[] myValues )  {
      for ( int i = 0; i < myKeys.Length; i++ )  {
         Console.WriteLine( "   {0,-10}: {1}", myKeys[i], myValues[i] );
      }
      Console.WriteLine();
   }
}


/*
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
open System
open System.Collections

type MyReverserClass() = 
    interface IComparer with
        member _.Compare(x, y) =
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let printKeysAndValues (myKeys: string []) (myValues: string []) =
    for i = 0 to myKeys.Length - 1 do
        printfn $"   {myKeys[i],-10}: {myValues[i]}"
    printfn ""

// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()

// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues 

// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:" 
printKeysAndValues myKeys myValues

// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues


// This code produces the following output.
//     The Array initially contains the following values:
//        red       : strawberries
//        GREEN     : PEARS
//        YELLOW    : LIMES
//        BLUE      : BERRIES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting a section of the Array using the default comparer:
//        red       : strawberries
//        BLUE      : BERRIES
//        GREEN     : PEARS
//        YELLOW    : LIMES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting a section of the Array using the reverse case-insensitive comparer:
//        red       : strawberries
//        YELLOW    : LIMES
//        GREEN     : PEARS
//        BLUE      : BERRIES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting the entire Array using the default comparer:
//        black     : olives
//        BLUE      : BERRIES
//        GREEN     : PEARS
//        orange    : cantaloupe
//        purple    : grapes
//        red       : strawberries
//        YELLOW    : LIMES
//     
//     After sorting the entire Array using the reverse case-insensitive comparer:
//        YELLOW    : LIMES
//        red       : strawberries
//        purple    : grapes
//        orange    : cantaloupe
//        GREEN     : PEARS
//        BLUE      : BERRIES
//        black     : olives
Imports System.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

      ' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      Function Compare(x As [Object], y As [Object]) As Integer _
         Implements IComparer.Compare
         Return New CaseInsensitiveComparer().Compare(y, x)
      End Function 'IComparer.Compare

   End Class


   Public Shared Sub Main()

      ' Creates and initializes a new Array and a new custom comparer.
      Dim myKeys As [String]() =  {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
      Dim myValues As [String]() =  {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
      Dim myComparer = New myReverserClass()

      ' Displays the values of the Array.
      Console.WriteLine("The Array initially contains the following values:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts a section of the Array using the default comparer.
      Array.Sort(myKeys, myValues, 1, 3)
      Console.WriteLine("After sorting a section of the Array using the default comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts a section of the Array using the reverse case-insensitive comparer.
      Array.Sort(myKeys, myValues, 1, 3, myComparer)
      Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts the entire Array using the default comparer.
      Array.Sort(myKeys, myValues)
      Console.WriteLine("After sorting the entire Array using the default comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts the entire Array using the reverse case-insensitive comparer.
      Array.Sort(myKeys, myValues, myComparer)
      Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
      PrintKeysAndValues(myKeys, myValues)

   End Sub


   Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])

      Dim i As Integer
      For i = 0 To myKeys.Length - 1
         Console.WriteLine("   {0,-10}: {1}", myKeys(i), myValues(i))
      Next i
      Console.WriteLine()

   End Sub

End Class


'This code produces the following output.
'
'The Array initially contains the following values:
'   red       : strawberries
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the default comparer:
'   red       : strawberries
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
'   red       : strawberries
'   YELLOW    : LIMES
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting the entire Array using the default comparer:
'   black     : olives
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   orange    : cantaloupe
'   purple    : grapes
'   red       : strawberries
'   YELLOW    : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
'   YELLOW    : LIMES
'   red       : strawberries
'   purple    : grapes
'   orange    : cantaloupe
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   black     : olives

설명

keysArray 각 키에는 에 해당 항목이 itemsArray있습니다. 정렬하는 동안 키의 위치가 변경되면 의 해당 항목 itemsArray 의 위치도 비슷하게 변경됩니다. 따라서 는 itemsArray 에서 해당 키의 정렬에 따라 정렬됩니다 keysArray.

의 지정된 요소 keysArray 범위 내의 각 키는 다른 모든 키와 비교할 수 있도록 인터페이스를 구현 IComparable 해야 합니다.

키보다 더 많은 항목이 있는 경우 정렬할 수 있지만 해당 키가 없는 항목은 정렬되지 않습니다. 항목보다 키가 더 많은 경우 정렬할 수 없습니다. 이렇게 하면 가 ArgumentExceptionthrow됩니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 2 * LogN을 초과하는 경우 여기서 N 은 입력 배열의 범위이며 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 정렬 알고리즘을 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

추가 정보

적용 대상

Sort(Array, Int32, Int32)

Array 에 있는 각 요소의 IComparable 구현을 사용하여 1차원 Array의 요소 범위에 있는 요소를 정렬합니다.

public:
 static void Sort(Array ^ array, int index, int length);
public static void Sort (Array array, int index, int length);
static member Sort : Array * int * int -> unit
Public Shared Sub Sort (array As Array, index As Integer, length As Integer)

매개 변수

array
Array

정렬할 1차원 Array 입니다.

index
Int32

정렬할 범위의 시작 인덱스입니다.

length
Int32

정렬할 범위에 있는 요소 수입니다.

예외

array이(가) null인 경우

array가 다차원 배열인 경우

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

또는

length가 0보다 작은 경우

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

array의 요소 중 하나 이상이 IComparable 인터페이스를 구현하지 않는 경우

예제

다음 코드 예제에서는 기본 비교자와 정렬 순서를 반대로 하는 사용자 지정 비교자를 사용하여 의 Array 값을 정렬하는 방법을 보여 줍니다. 결과는 현재 CultureInfo에 따라 달라질 수 있습니다.

using namespace System;
using namespace System::Collections;

public ref class ReverseComparer : IComparer
{
public:
   // Call CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
   }
};

void DisplayValues(array<String^>^ arr)
{
   for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
      Console::WriteLine( "   [{0}] : {1}", i, arr[ i ] );

   Console::WriteLine();
}

int main()
{
   // Create and initialize a new array. and a new custom comparer.
   array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
                             "over","the","lazy","dog" };
   // Instantiate the reverse comparer.
   IComparer^ revComparer = gcnew ReverseComparer();
   
   // Display the values of the Array.
   Console::WriteLine( "The original order of elements in the array:" );
   DisplayValues(words);

   // Sort a section of the array using the default comparer.
   Array::Sort(words, 1, 3);
   Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
   DisplayValues(words);

   // Sort a section of the array using the reverse case-insensitive comparer.
   Array::Sort(words, 1, 3, revComparer);
   Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
   DisplayValues(words);

   // Sort the entire array using the default comparer.
   Array::Sort(words);
   Console::WriteLine( "After sorting the entire array by using the default comparer:");
   DisplayValues(words);

   // Sort the entire array by using the reverse case-insensitive comparer.
   Array::Sort(words, revComparer);
   Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
   DisplayValues(words);
}

/* 
This code produces the following output.

The Array initially contains the following values:
   [0] : The
   [1] : QUICK
   [2] : BROWN
   [3] : FOX
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the default comparer:
   [0] : The
   [1] : BROWN
   [2] : FOX
   [3] : QUICK
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the reverse case-insensitive comparer:
   [0] : The
   [1] : QUICK
   [2] : FOX
   [3] : BROWN
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting the entire Array using the default comparer:
   [0] : BROWN
   [1] : dog
   [2] : FOX
   [3] : jumps
   [4] : lazy
   [5] : over
   [6] : QUICK
   [7] : the
   [8] : The

After sorting the entire Array using the reverse case-insensitive comparer:
   [0] : the
   [1] : The
   [2] : QUICK
   [3] : over
   [4] : lazy
   [5] : jumps
   [6] : FOX
   [7] : dog
   [8] : BROWN

*/
using System;
using System.Collections;

public class ReverseComparer : IComparer
{
   // Call CaseInsensitiveComparer.Compare with the parameters reversed.
   public int Compare(Object x, Object y)
   {
       return (new CaseInsensitiveComparer()).Compare(y, x );
   }
}

public class Example
{
   public static void Main()
   {
      // Create and initialize a new array.
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps",
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();

      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);

      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

      // Sort a section of the array using the reverse case-insensitive comparer.
      Array.Sort(words, 1, 3, revComparer);
      Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
      DisplayValues(words);

      // Sort the entire array using the default comparer.
      Array.Sort(words);
      Console.WriteLine( "After sorting the entire array by using the default comparer:");
      DisplayValues(words);

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }

   public static void DisplayValues(String[] arr)
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
open System
open System.Collections

type ReverseComparer() =
    interface IComparer with
        member _.Compare(x, y) =
            // Call CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let displayValues (arr: string []) = 
    for i = 0 to arr.Length - 1 do
        printfn $"   [{i}] : {arr[i]}"
    printfn ""

// Create and initialize a new array.
let words = 
    [| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
       "over"; "the"; "lazy"; "dog" |]

// Instantiate the reverse comparer.
let revComparer = ReverseComparer()

// Display the values of the array.
printfn "The original order of elements in the array:" 
displayValues words

// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
printfn "After sorting elements 1-3 by using the default comparer:"
displayValues words

// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
printfn "After sorting elements 1-3 by using the reverse case-insensitive comparer:"
displayValues words

// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words

// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words

// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
Imports System.Collections

Public Class ReverseComparer : Implements IComparer
   ' Call CaseInsensitiveComparer.Compare with the parameters reversed.
   Function Compare(x As Object, y As Object) As Integer _
            Implements IComparer.Compare
      Return New CaseInsensitiveComparer().Compare(y, x)
   End Function 
End Class

Public Module Example
   Public Sub Main()
      ' Create and initialize a new array.
      Dim words() As String =  { "The", "QUICK", "BROWN", "FOX", "jumps", 
                                 "over", "the", "lazy", "dog" }
      ' Instantiate a new custom comparer.
      Dim revComparer As New ReverseComparer()

      ' Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" )
      DisplayValues(words)

      ' Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3)
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:")
      DisplayValues(words)

      ' Sort a section of the array using the reverse case-insensitive comparer.
      Array.Sort(words, 1, 3, revComparer)
      Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:")
      DisplayValues(words)

      ' Sort the entire array using the default comparer.
      Array.Sort(words)
      Console.WriteLine( "After sorting the entire array by using the default comparer:")
      DisplayValues(words)

      ' Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer)
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:")
      DisplayValues(words)
   End Sub 

   Public Sub DisplayValues(arr() As String)
      For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
         Console.WriteLine("   [{0}] : {1}", i, arr(i))
      Next 
      Console.WriteLine()
   End Sub 
End Module 
' The example displays the following output:
'    The original order of elements in the array:
'       [0] : The
'       [1] : QUICK
'       [2] : BROWN
'       [3] : FOX
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting elements 1-3 by using the default comparer:
'       [0] : The
'       [1] : BROWN
'       [2] : FOX
'       [3] : QUICK
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting elements 1-3 by using the reverse case-insensitive comparer:
'       [0] : The
'       [1] : QUICK
'       [2] : FOX
'       [3] : BROWN
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting the entire array by using the default comparer:
'       [0] : BROWN
'       [1] : dog
'       [2] : FOX
'       [3] : jumps
'       [4] : lazy
'       [5] : over
'       [6] : QUICK
'       [7] : the
'       [8] : The
'    
'    After sorting the entire array using the reverse case-insensitive comparer:
'       [0] : the
'       [1] : The
'       [2] : QUICK
'       [3] : over
'       [4] : lazy
'       [5] : jumps
'       [6] : FOX
'       [7] : dog
'       [8] : BROWN

설명

의 지정된 요소 범위 내의 각 요소는 의 다른 모든 요소 arrayarray와 비교할 수 있도록 인터페이스를 구현 IComparable 해야 합니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 2 * LogN을 초과하는 경우 여기서 N 은 입력 배열의 범위이며 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 정렬 알고리즘을 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

추가 정보

적용 대상

Sort(Array, Array, IComparer)

지정한 Array 를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 1차원 IComparer개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)를 정렬합니다.

public:
 static void Sort(Array ^ keys, Array ^ items, System::Collections::IComparer ^ comparer);
public static void Sort (Array keys, Array items, System.Collections.IComparer comparer);
public static void Sort (Array keys, Array? items, System.Collections.IComparer? comparer);
static member Sort : Array * Array * System.Collections.IComparer -> unit
Public Shared Sub Sort (keys As Array, items As Array, comparer As IComparer)

매개 변수

keys
Array

정렬할 키를 포함하는 1차원 Array 입니다.

items
Array

keysArray의 각 키에 해당하는 항목을 포함하는 1차원 Array입니다.

또는

keysArray만을 정렬하는 null입니다.

comparer
IComparer

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

또는

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

예외

keys이(가) null인 경우

keysArray가 다차원 배열입니다.

또는

itemsArray가 다차원 배열입니다.

itemsnull이 아니고 keys 의 길이가 items의 길이보다 큽니다.

또는

comparer의 구현으로 인해 정렬 중에 오류가 발생했습니다. 예를 들어 항목을 자기 자신과 비교할 때 comparer에서 0을 반환하지 않을 수 있습니다.

comparernull이고 keysArray 의 하나 이상의 요소가 IComparable 인터페이스를 구현하지 않습니다.

예제

다음 예제에서는 첫 번째 배열에 키가 포함되고 두 번째 배열에 값이 포함된 두 개의 연결된 배열을 정렬하는 방법을 보여 줍니다. 정렬은 정렬 순서를 반대로 하는 기본 비교자와 사용자 지정 비교자를 사용하여 수행됩니다. 결과는 현재 CultureInfo에 따라 달라질 수 있습니다.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

   // Calls CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
   }
};

void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
   for ( int i = 0; i < myKeys->Length; i++ )
   {
      Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
   }
   Console::WriteLine();
}

int main()
{
   // Creates and initializes a new Array and a new custom comparer.
   array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
   array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
   IComparer^ myComparer = gcnew myReverserClass;

   // Displays the values of the Array.
   Console::WriteLine( "The Array initially contains the following values:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts a section of the Array using the default comparer.
   Array::Sort( myKeys, myValues, 1, 3 );
   Console::WriteLine( "After sorting a section of the Array using the default comparer:" );

   // Sorts a section of the Array using the reverse case-insensitive comparer.
   Array::Sort( myKeys, myValues, 1, 3, myComparer );
   Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts the entire Array using the default comparer.
   Array::Sort( myKeys, myValues );
   Console::WriteLine( "After sorting the entire Array using the default comparer:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts the entire Array using the reverse case-insensitive comparer.
   Array::Sort( myKeys, myValues, myComparer );
   Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
   PrintKeysAndValues( myKeys, myValues );
}

/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
using System;
using System.Collections;

public class SamplesArray  {

   public class myReverserClass : IComparer  {

      // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }
   }

   public static void Main()  {

      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();

      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts a section of the Array using the reverse case-insensitive comparer.
      Array.Sort( myKeys, myValues, 1, 3, myComparer );
      Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts the entire Array using the default comparer.
      Array.Sort( myKeys, myValues );
      Console.WriteLine( "After sorting the entire Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts the entire Array using the reverse case-insensitive comparer.
      Array.Sort( myKeys, myValues, myComparer );
      Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
      PrintKeysAndValues( myKeys, myValues );
   }

   public static void PrintKeysAndValues( String[] myKeys, String[] myValues )  {
      for ( int i = 0; i < myKeys.Length; i++ )  {
         Console.WriteLine( "   {0,-10}: {1}", myKeys[i], myValues[i] );
      }
      Console.WriteLine();
   }
}


/*
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
open System
open System.Collections

type MyReverserClass() = 
    interface IComparer with
        member _.Compare(x, y) =
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let printKeysAndValues (myKeys: string []) (myValues: string []) =
    for i = 0 to myKeys.Length - 1 do
        printfn $"   {myKeys[i],-10}: {myValues[i]}"
    printfn ""

// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()

// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues 

// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:" 
printKeysAndValues myKeys myValues

// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues


// This code produces the following output.
//     The Array initially contains the following values:
//        red       : strawberries
//        GREEN     : PEARS
//        YELLOW    : LIMES
//        BLUE      : BERRIES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting a section of the Array using the default comparer:
//        red       : strawberries
//        BLUE      : BERRIES
//        GREEN     : PEARS
//        YELLOW    : LIMES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting a section of the Array using the reverse case-insensitive comparer:
//        red       : strawberries
//        YELLOW    : LIMES
//        GREEN     : PEARS
//        BLUE      : BERRIES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting the entire Array using the default comparer:
//        black     : olives
//        BLUE      : BERRIES
//        GREEN     : PEARS
//        orange    : cantaloupe
//        purple    : grapes
//        red       : strawberries
//        YELLOW    : LIMES
//     
//     After sorting the entire Array using the reverse case-insensitive comparer:
//        YELLOW    : LIMES
//        red       : strawberries
//        purple    : grapes
//        orange    : cantaloupe
//        GREEN     : PEARS
//        BLUE      : BERRIES
//        black     : olives
Imports System.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

      ' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      Function Compare(x As [Object], y As [Object]) As Integer _
         Implements IComparer.Compare
         Return New CaseInsensitiveComparer().Compare(y, x)
      End Function 'IComparer.Compare

   End Class


   Public Shared Sub Main()

      ' Creates and initializes a new Array and a new custom comparer.
      Dim myKeys As [String]() =  {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
      Dim myValues As [String]() =  {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
      Dim myComparer = New myReverserClass()

      ' Displays the values of the Array.
      Console.WriteLine("The Array initially contains the following values:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts a section of the Array using the default comparer.
      Array.Sort(myKeys, myValues, 1, 3)
      Console.WriteLine("After sorting a section of the Array using the default comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts a section of the Array using the reverse case-insensitive comparer.
      Array.Sort(myKeys, myValues, 1, 3, myComparer)
      Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts the entire Array using the default comparer.
      Array.Sort(myKeys, myValues)
      Console.WriteLine("After sorting the entire Array using the default comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts the entire Array using the reverse case-insensitive comparer.
      Array.Sort(myKeys, myValues, myComparer)
      Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
      PrintKeysAndValues(myKeys, myValues)

   End Sub


   Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])

      Dim i As Integer
      For i = 0 To myKeys.Length - 1
         Console.WriteLine("   {0,-10}: {1}", myKeys(i), myValues(i))
      Next i
      Console.WriteLine()

   End Sub

End Class


'This code produces the following output.
'
'The Array initially contains the following values:
'   red       : strawberries
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the default comparer:
'   red       : strawberries
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
'   red       : strawberries
'   YELLOW    : LIMES
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting the entire Array using the default comparer:
'   black     : olives
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   orange    : cantaloupe
'   purple    : grapes
'   red       : strawberries
'   YELLOW    : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
'   YELLOW    : LIMES
'   red       : strawberries
'   purple    : grapes
'   orange    : cantaloupe
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   black     : olives

설명

keysArray 각 키에는 에 해당 항목이 itemsArray있습니다. 정렬하는 동안 키의 위치가 변경되면 의 해당 항목 itemsArray 의 위치도 비슷하게 변경됩니다. 따라서 는 itemsArray 에서 해당 키의 정렬에 따라 정렬됩니다 keysArray.

가 이nullcomparerkeysArray 각 키는 다른 모든 키와 비교할 수 있도록 인터페이스를 구현 IComparable 해야 합니다.

키보다 더 많은 항목이 있는 경우 정렬할 수 있지만 해당 키가 없는 항목은 정렬되지 않습니다. 항목보다 키가 더 많은 경우 정렬할 수 없습니다. 이렇게 하면 가 ArgumentExceptionthrow됩니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

.NET에는 다음 표에 나열된 미리 정의된 IComparer 구현이 포함되어 있습니다.

구현 설명
System.Collections.CaseInsensitiveComparer 두 개체를 비교하지만 문자열의 대/소문자를 구분하지 않는 비교를 수행합니다.
Comparer.Default 현재 문화권의 정렬 규칙을 사용하여 두 개체를 비교합니다.
Comparer.DefaultInvariant 고정 문화권의 정렬 규칙을 사용하여 두 개체를 비교합니다.
Comparer<T>.Default 형식의 기본 정렬 순서를 사용하여 형식 T 의 두 개체를 비교합니다.

매개 변수에 고유한 IComparer 구현의 instance 제공하여 사용자 지정 비교를 comparer 지원할 수도 있습니다. 이 예제에서는 기본 정렬 순서를 IComparer 반대로 하고 대/소문자를 구분하지 않는 문자열 비교를 수행하는 구현을 정의하여 이 작업을 수행합니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 2 * LogN을 초과하는 경우 여기서 N 은 입력 배열의 범위이며 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 정렬 알고리즘을 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

호출자 참고

.NET Framework 4 이전 버전에서는 빠른 정렬 알고리즘만 사용했습니다. Quicksort는 정렬 작업이 예외를 throw하고 호출자에게 예외를 throw IndexOutOfRangeException 하는 일부 상황에서 잘못된 비교자를 식별합니다 ArgumentException . .NET Framework 4.5부터는 삽입 정렬 및 힙소트 알고리즘이 잘못된 비교자를 검색하지 않으므로 이전에 던진 ArgumentException 정렬 작업에서 예외를 throw하지 않을 수 있습니다. 대부분의 경우 16개 요소보다 작거나 같은 배열에 적용됩니다.

추가 정보

적용 대상

Sort(Array, Array)

Array 구현을 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 1차원 IComparable 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)를 정렬합니다.

public:
 static void Sort(Array ^ keys, Array ^ items);
public static void Sort (Array keys, Array items);
public static void Sort (Array keys, Array? items);
static member Sort : Array * Array -> unit
Public Shared Sub Sort (keys As Array, items As Array)

매개 변수

keys
Array

정렬할 키를 포함하는 1차원 Array 입니다.

items
Array

keysArray의 각 키에 해당하는 항목을 포함하는 1차원 Array입니다.

또는

keysArray만을 정렬하는 null입니다.

예외

keys이(가) null인 경우

keysArray가 다차원 배열입니다.

또는

itemsArray가 다차원 배열입니다.

itemsnull이 아니고 keys 의 길이가 items의 길이보다 큽니다.

keysArray의 요소 중 하나 이상이 IComparable 인터페이스를 구현하지 않습니다.

예제

다음 예제에서는 첫 번째 배열에 키가 포함되고 두 번째 배열에 값이 포함된 두 개의 연결된 배열을 정렬하는 방법을 보여 줍니다. 정렬은 정렬 순서를 반대로 하는 기본 비교자와 사용자 지정 비교자를 사용하여 수행됩니다. 결과는 현재 CultureInfo에 따라 달라질 수 있습니다.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

   // Calls CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
   }
};

void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
   for ( int i = 0; i < myKeys->Length; i++ )
   {
      Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
   }
   Console::WriteLine();
}

int main()
{
   // Creates and initializes a new Array and a new custom comparer.
   array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
   array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
   IComparer^ myComparer = gcnew myReverserClass;

   // Displays the values of the Array.
   Console::WriteLine( "The Array initially contains the following values:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts a section of the Array using the default comparer.
   Array::Sort( myKeys, myValues, 1, 3 );
   Console::WriteLine( "After sorting a section of the Array using the default comparer:" );

   // Sorts a section of the Array using the reverse case-insensitive comparer.
   Array::Sort( myKeys, myValues, 1, 3, myComparer );
   Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts the entire Array using the default comparer.
   Array::Sort( myKeys, myValues );
   Console::WriteLine( "After sorting the entire Array using the default comparer:" );
   PrintKeysAndValues( myKeys, myValues );

   // Sorts the entire Array using the reverse case-insensitive comparer.
   Array::Sort( myKeys, myValues, myComparer );
   Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
   PrintKeysAndValues( myKeys, myValues );
}

/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
using System;
using System.Collections;

public class SamplesArray  {

   public class myReverserClass : IComparer  {

      // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }
   }

   public static void Main()  {

      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();

      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts a section of the Array using the reverse case-insensitive comparer.
      Array.Sort( myKeys, myValues, 1, 3, myComparer );
      Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts the entire Array using the default comparer.
      Array.Sort( myKeys, myValues );
      Console.WriteLine( "After sorting the entire Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

      // Sorts the entire Array using the reverse case-insensitive comparer.
      Array.Sort( myKeys, myValues, myComparer );
      Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
      PrintKeysAndValues( myKeys, myValues );
   }

   public static void PrintKeysAndValues( String[] myKeys, String[] myValues )  {
      for ( int i = 0; i < myKeys.Length; i++ )  {
         Console.WriteLine( "   {0,-10}: {1}", myKeys[i], myValues[i] );
      }
      Console.WriteLine();
   }
}


/*
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
open System
open System.Collections

type MyReverserClass() = 
    interface IComparer with
        member _.Compare(x, y) =
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let printKeysAndValues (myKeys: string []) (myValues: string []) =
    for i = 0 to myKeys.Length - 1 do
        printfn $"   {myKeys[i],-10}: {myValues[i]}"
    printfn ""

// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()

// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues 

// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:" 
printKeysAndValues myKeys myValues

// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues


// This code produces the following output.
//     The Array initially contains the following values:
//        red       : strawberries
//        GREEN     : PEARS
//        YELLOW    : LIMES
//        BLUE      : BERRIES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting a section of the Array using the default comparer:
//        red       : strawberries
//        BLUE      : BERRIES
//        GREEN     : PEARS
//        YELLOW    : LIMES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting a section of the Array using the reverse case-insensitive comparer:
//        red       : strawberries
//        YELLOW    : LIMES
//        GREEN     : PEARS
//        BLUE      : BERRIES
//        purple    : grapes
//        black     : olives
//        orange    : cantaloupe
//     
//     After sorting the entire Array using the default comparer:
//        black     : olives
//        BLUE      : BERRIES
//        GREEN     : PEARS
//        orange    : cantaloupe
//        purple    : grapes
//        red       : strawberries
//        YELLOW    : LIMES
//     
//     After sorting the entire Array using the reverse case-insensitive comparer:
//        YELLOW    : LIMES
//        red       : strawberries
//        purple    : grapes
//        orange    : cantaloupe
//        GREEN     : PEARS
//        BLUE      : BERRIES
//        black     : olives
Imports System.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

      ' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      Function Compare(x As [Object], y As [Object]) As Integer _
         Implements IComparer.Compare
         Return New CaseInsensitiveComparer().Compare(y, x)
      End Function 'IComparer.Compare

   End Class


   Public Shared Sub Main()

      ' Creates and initializes a new Array and a new custom comparer.
      Dim myKeys As [String]() =  {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
      Dim myValues As [String]() =  {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
      Dim myComparer = New myReverserClass()

      ' Displays the values of the Array.
      Console.WriteLine("The Array initially contains the following values:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts a section of the Array using the default comparer.
      Array.Sort(myKeys, myValues, 1, 3)
      Console.WriteLine("After sorting a section of the Array using the default comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts a section of the Array using the reverse case-insensitive comparer.
      Array.Sort(myKeys, myValues, 1, 3, myComparer)
      Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts the entire Array using the default comparer.
      Array.Sort(myKeys, myValues)
      Console.WriteLine("After sorting the entire Array using the default comparer:")
      PrintKeysAndValues(myKeys, myValues)

      ' Sorts the entire Array using the reverse case-insensitive comparer.
      Array.Sort(myKeys, myValues, myComparer)
      Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
      PrintKeysAndValues(myKeys, myValues)

   End Sub


   Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])

      Dim i As Integer
      For i = 0 To myKeys.Length - 1
         Console.WriteLine("   {0,-10}: {1}", myKeys(i), myValues(i))
      Next i
      Console.WriteLine()

   End Sub

End Class


'This code produces the following output.
'
'The Array initially contains the following values:
'   red       : strawberries
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the default comparer:
'   red       : strawberries
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
'   red       : strawberries
'   YELLOW    : LIMES
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting the entire Array using the default comparer:
'   black     : olives
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   orange    : cantaloupe
'   purple    : grapes
'   red       : strawberries
'   YELLOW    : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
'   YELLOW    : LIMES
'   red       : strawberries
'   purple    : grapes
'   orange    : cantaloupe
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   black     : olives

설명

keysArray 각 키에는 에 해당 항목이 itemsArray있습니다. 정렬하는 동안 키의 위치가 변경되면 의 해당 항목 itemsArray 의 위치도 비슷하게 변경됩니다. 따라서 는 itemsArray 에서 해당 키의 정렬에 따라 정렬됩니다 keysArray.

의 각 키는 keysArray 다른 모든 키와 비교할 수 있도록 인터페이스를 구현 IComparable 해야 합니다.

키보다 더 많은 항목이 있는 경우 정렬할 수 있지만 해당 키가 없는 항목은 정렬되지 않습니다. 항목보다 키가 더 많은 경우 정렬할 수 없습니다. 이렇게 하면 가 ArgumentExceptionthrow됩니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 2 * LogN을 초과하는 경우 여기서 N 은 입력 배열의 범위이며 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 정렬 알고리즘을 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

추가 정보

적용 대상

Sort(Array)

Array 에 있는 각 요소의 IComparable 구현을 사용하여 1차원 Array전체의 요소를 정렬합니다.

public:
 static void Sort(Array ^ array);
public static void Sort (Array array);
static member Sort : Array -> unit
Public Shared Sub Sort (array As Array)

매개 변수

array
Array

정렬할 1차원 Array 입니다.

예외

array이(가) null인 경우

array가 다차원 배열인 경우

array의 요소 중 하나 이상이 IComparable 인터페이스를 구현하지 않는 경우

예제

다음 코드 예제에서는 기본 비교자와 정렬 순서를 반대로 하는 사용자 지정 비교자를 사용하여 의 Array 값을 정렬하는 방법을 보여 줍니다. 결과는 현재 CultureInfo에 따라 달라질 수 있습니다.

using namespace System;
using namespace System::Collections;

public ref class ReverseComparer : IComparer
{
public:
   // Call CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
   }
};

void DisplayValues(array<String^>^ arr)
{
   for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
      Console::WriteLine( "   [{0}] : {1}", i, arr[ i ] );

   Console::WriteLine();
}

int main()
{
   // Create and initialize a new array. and a new custom comparer.
   array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
                             "over","the","lazy","dog" };
   // Instantiate the reverse comparer.
   IComparer^ revComparer = gcnew ReverseComparer();
   
   // Display the values of the Array.
   Console::WriteLine( "The original order of elements in the array:" );
   DisplayValues(words);

   // Sort a section of the array using the default comparer.
   Array::Sort(words, 1, 3);
   Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
   DisplayValues(words);

   // Sort a section of the array using the reverse case-insensitive comparer.
   Array::Sort(words, 1, 3, revComparer);
   Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
   DisplayValues(words);

   // Sort the entire array using the default comparer.
   Array::Sort(words);
   Console::WriteLine( "After sorting the entire array by using the default comparer:");
   DisplayValues(words);

   // Sort the entire array by using the reverse case-insensitive comparer.
   Array::Sort(words, revComparer);
   Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
   DisplayValues(words);
}

/* 
This code produces the following output.

The Array initially contains the following values:
   [0] : The
   [1] : QUICK
   [2] : BROWN
   [3] : FOX
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the default comparer:
   [0] : The
   [1] : BROWN
   [2] : FOX
   [3] : QUICK
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the reverse case-insensitive comparer:
   [0] : The
   [1] : QUICK
   [2] : FOX
   [3] : BROWN
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting the entire Array using the default comparer:
   [0] : BROWN
   [1] : dog
   [2] : FOX
   [3] : jumps
   [4] : lazy
   [5] : over
   [6] : QUICK
   [7] : the
   [8] : The

After sorting the entire Array using the reverse case-insensitive comparer:
   [0] : the
   [1] : The
   [2] : QUICK
   [3] : over
   [4] : lazy
   [5] : jumps
   [6] : FOX
   [7] : dog
   [8] : BROWN

*/
using System;
using System.Collections;

public class ReverseComparer : IComparer
{
   // Call CaseInsensitiveComparer.Compare with the parameters reversed.
   public int Compare(Object x, Object y)
   {
       return (new CaseInsensitiveComparer()).Compare(y, x );
   }
}

public class Example
{
   public static void Main()
   {
      // Create and initialize a new array.
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps",
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();

      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);

      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

      // Sort a section of the array using the reverse case-insensitive comparer.
      Array.Sort(words, 1, 3, revComparer);
      Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
      DisplayValues(words);

      // Sort the entire array using the default comparer.
      Array.Sort(words);
      Console.WriteLine( "After sorting the entire array by using the default comparer:");
      DisplayValues(words);

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }

   public static void DisplayValues(String[] arr)
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
open System
open System.Collections

type ReverseComparer() =
    interface IComparer with
        member _.Compare(x, y) =
            // Call CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let displayValues (arr: string []) = 
    for i = 0 to arr.Length - 1 do
        printfn $"   [{i}] : {arr[i]}"
    printfn ""

// Create and initialize a new array.
let words = 
    [| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
       "over"; "the"; "lazy"; "dog" |]

// Instantiate the reverse comparer.
let revComparer = ReverseComparer()

// Display the values of the array.
printfn "The original order of elements in the array:" 
displayValues words

// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
printfn "After sorting elements 1-3 by using the default comparer:"
displayValues words

// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
printfn "After sorting elements 1-3 by using the reverse case-insensitive comparer:"
displayValues words

// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words

// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words

// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
Imports System.Collections

Public Class ReverseComparer : Implements IComparer
   ' Call CaseInsensitiveComparer.Compare with the parameters reversed.
   Function Compare(x As Object, y As Object) As Integer _
            Implements IComparer.Compare
      Return New CaseInsensitiveComparer().Compare(y, x)
   End Function 
End Class

Public Module Example
   Public Sub Main()
      ' Create and initialize a new array.
      Dim words() As String =  { "The", "QUICK", "BROWN", "FOX", "jumps", 
                                 "over", "the", "lazy", "dog" }
      ' Instantiate a new custom comparer.
      Dim revComparer As New ReverseComparer()

      ' Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" )
      DisplayValues(words)

      ' Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3)
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:")
      DisplayValues(words)

      ' Sort a section of the array using the reverse case-insensitive comparer.
      Array.Sort(words, 1, 3, revComparer)
      Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:")
      DisplayValues(words)

      ' Sort the entire array using the default comparer.
      Array.Sort(words)
      Console.WriteLine( "After sorting the entire array by using the default comparer:")
      DisplayValues(words)

      ' Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer)
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:")
      DisplayValues(words)
   End Sub 

   Public Sub DisplayValues(arr() As String)
      For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
         Console.WriteLine("   [{0}] : {1}", i, arr(i))
      Next 
      Console.WriteLine()
   End Sub 
End Module 
' The example displays the following output:
'    The original order of elements in the array:
'       [0] : The
'       [1] : QUICK
'       [2] : BROWN
'       [3] : FOX
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting elements 1-3 by using the default comparer:
'       [0] : The
'       [1] : BROWN
'       [2] : FOX
'       [3] : QUICK
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting elements 1-3 by using the reverse case-insensitive comparer:
'       [0] : The
'       [1] : QUICK
'       [2] : FOX
'       [3] : BROWN
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting the entire array by using the default comparer:
'       [0] : BROWN
'       [1] : dog
'       [2] : FOX
'       [3] : jumps
'       [4] : lazy
'       [5] : over
'       [6] : QUICK
'       [7] : the
'       [8] : The
'    
'    After sorting the entire array using the reverse case-insensitive comparer:
'       [0] : the
'       [1] : The
'       [2] : QUICK
'       [3] : over
'       [4] : lazy
'       [5] : jumps
'       [6] : FOX
'       [7] : dog
'       [8] : BROWN

설명

array 각 요소는 의 다른 모든 요소array와 비교할 수 있도록 인터페이스를 구현 IComparable 해야 합니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 2 * LogN을 초과하는 경우 여기서 N 은 입력 배열의 범위이며 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 정렬 알고리즘을 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

추가 정보

적용 대상

Sort(Array, IComparer)

지정한 Array 를 사용하여 1차원 IComparer의 요소를 정렬합니다.

public:
 static void Sort(Array ^ array, System::Collections::IComparer ^ comparer);
public static void Sort (Array array, System.Collections.IComparer comparer);
public static void Sort (Array array, System.Collections.IComparer? comparer);
static member Sort : Array * System.Collections.IComparer -> unit
Public Shared Sub Sort (array As Array, comparer As IComparer)

매개 변수

array
Array

정렬할 1차원 배열입니다.

comparer
IComparer

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

또는

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

예외

array이(가) null인 경우

array가 다차원 배열인 경우

comparernull이고 array의 요소 중 하나 이상이 IComparable 인터페이스를 구현하지 않는 경우

comparer의 구현으로 인해 정렬 중에 오류가 발생했습니다. 예를 들어 항목을 자기 자신과 비교할 때 comparer에서 0을 반환하지 않을 수 있습니다.

예제

다음 예제에서는 기본 비교자를 사용하여 문자열 배열의 값을 정렬합니다. 또한 대/소문자를 구분하지 않는 문자열 비교를 수행하는 동안 개체의 기본 정렬 순서를 반대로 하는 라는 ReverseComparer 사용자 지정 IComparer 구현을 정의합니다. 출력은 현재 문화권에 따라 달라질 수 있습니다.

using namespace System;
using namespace System::Collections;

public ref class ReverseComparer : IComparer
{
public:
   // Call CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
   }
};

void DisplayValues(array<String^>^ arr)
{
   for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
      Console::WriteLine( "   [{0}] : {1}", i, arr[ i ] );

   Console::WriteLine();
}

int main()
{
   // Create and initialize a new array. and a new custom comparer.
   array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
                             "over","the","lazy","dog" };
   // Instantiate the reverse comparer.
   IComparer^ revComparer = gcnew ReverseComparer();
   
   // Display the values of the Array.
   Console::WriteLine( "The original order of elements in the array:" );
   DisplayValues(words);

   // Sort a section of the array using the default comparer.
   Array::Sort(words, 1, 3);
   Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
   DisplayValues(words);

   // Sort a section of the array using the reverse case-insensitive comparer.
   Array::Sort(words, 1, 3, revComparer);
   Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
   DisplayValues(words);

   // Sort the entire array using the default comparer.
   Array::Sort(words);
   Console::WriteLine( "After sorting the entire array by using the default comparer:");
   DisplayValues(words);

   // Sort the entire array by using the reverse case-insensitive comparer.
   Array::Sort(words, revComparer);
   Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
   DisplayValues(words);
}

/* 
This code produces the following output.

The Array initially contains the following values:
   [0] : The
   [1] : QUICK
   [2] : BROWN
   [3] : FOX
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the default comparer:
   [0] : The
   [1] : BROWN
   [2] : FOX
   [3] : QUICK
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the reverse case-insensitive comparer:
   [0] : The
   [1] : QUICK
   [2] : FOX
   [3] : BROWN
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting the entire Array using the default comparer:
   [0] : BROWN
   [1] : dog
   [2] : FOX
   [3] : jumps
   [4] : lazy
   [5] : over
   [6] : QUICK
   [7] : the
   [8] : The

After sorting the entire Array using the reverse case-insensitive comparer:
   [0] : the
   [1] : The
   [2] : QUICK
   [3] : over
   [4] : lazy
   [5] : jumps
   [6] : FOX
   [7] : dog
   [8] : BROWN

*/
using System;
using System.Collections;

public class ReverseComparer : IComparer
{
   // Call CaseInsensitiveComparer.Compare with the parameters reversed.
   public int Compare(Object x, Object y)
   {
       return (new CaseInsensitiveComparer()).Compare(y, x );
   }
}

public class Example
{
   public static void Main()
   {
      // Create and initialize a new array.
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps",
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();

      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);

      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

      // Sort a section of the array using the reverse case-insensitive comparer.
      Array.Sort(words, 1, 3, revComparer);
      Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
      DisplayValues(words);

      // Sort the entire array using the default comparer.
      Array.Sort(words);
      Console.WriteLine( "After sorting the entire array by using the default comparer:");
      DisplayValues(words);

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }

   public static void DisplayValues(String[] arr)
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
open System
open System.Collections

type ReverseComparer() =
    interface IComparer with
        member _.Compare(x, y) =
            // Call CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let displayValues (arr: string []) = 
    for i = 0 to arr.Length - 1 do
        printfn $"   [{i}] : {arr[i]}"
    printfn ""

// Create and initialize a new array.
let words = 
    [| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
       "over"; "the"; "lazy"; "dog" |]

// Instantiate the reverse comparer.
let revComparer = ReverseComparer()

// Display the values of the array.
printfn "The original order of elements in the array:" 
displayValues words

// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
printfn "After sorting elements 1-3 by using the default comparer:"
displayValues words

// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
printfn "After sorting elements 1-3 by using the reverse case-insensitive comparer:"
displayValues words

// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words

// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words

// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
Imports System.Collections

Public Class ReverseComparer : Implements IComparer
   ' Call CaseInsensitiveComparer.Compare with the parameters reversed.
   Function Compare(x As Object, y As Object) As Integer _
            Implements IComparer.Compare
      Return New CaseInsensitiveComparer().Compare(y, x)
   End Function 
End Class

Public Module Example
   Public Sub Main()
      ' Create and initialize a new array.
      Dim words() As String =  { "The", "QUICK", "BROWN", "FOX", "jumps", 
                                 "over", "the", "lazy", "dog" }
      ' Instantiate a new custom comparer.
      Dim revComparer As New ReverseComparer()

      ' Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" )
      DisplayValues(words)

      ' Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3)
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:")
      DisplayValues(words)

      ' Sort a section of the array using the reverse case-insensitive comparer.
      Array.Sort(words, 1, 3, revComparer)
      Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:")
      DisplayValues(words)

      ' Sort the entire array using the default comparer.
      Array.Sort(words)
      Console.WriteLine( "After sorting the entire array by using the default comparer:")
      DisplayValues(words)

      ' Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer)
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:")
      DisplayValues(words)
   End Sub 

   Public Sub DisplayValues(arr() As String)
      For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
         Console.WriteLine("   [{0}] : {1}", i, arr(i))
      Next 
      Console.WriteLine()
   End Sub 
End Module 
' The example displays the following output:
'    The original order of elements in the array:
'       [0] : The
'       [1] : QUICK
'       [2] : BROWN
'       [3] : FOX
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting elements 1-3 by using the default comparer:
'       [0] : The
'       [1] : BROWN
'       [2] : FOX
'       [3] : QUICK
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting elements 1-3 by using the reverse case-insensitive comparer:
'       [0] : The
'       [1] : QUICK
'       [2] : FOX
'       [3] : BROWN
'       [4] : jumps
'       [5] : over
'       [6] : the
'       [7] : lazy
'       [8] : dog
'    
'    After sorting the entire array by using the default comparer:
'       [0] : BROWN
'       [1] : dog
'       [2] : FOX
'       [3] : jumps
'       [4] : lazy
'       [5] : over
'       [6] : QUICK
'       [7] : the
'       [8] : The
'    
'    After sorting the entire array using the reverse case-insensitive comparer:
'       [0] : the
'       [1] : The
'       [2] : QUICK
'       [3] : over
'       [4] : lazy
'       [5] : jumps
'       [6] : FOX
'       [7] : dog
'       [8] : BROWN

설명

가 이nullcomparerarray 각 요소는 의 다른 모든 요소array와 비교할 수 있도록 인터페이스를 구현 IComparable 해야 합니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 입력 배열의 범위인 2 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 구성 알고리즘 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

.NET에는 다음 표에 나열된 미리 정의된 IComparer 구현이 포함되어 있습니다.

구현 설명
System.Collections.CaseInsensitiveComparer 두 개체를 비교하지만 문자열의 대/소문자를 구분하지 않는 비교를 수행합니다.
Comparer.Default 현재 문화권의 정렬 규칙을 사용하여 두 개체를 비교합니다.
Comparer.DefaultInvariant 고정 문화권의 정렬 규칙을 사용하여 두 개체를 비교합니다.
Comparer<T>.Default 형식의 기본 정렬 순서를 사용하여 형식 T 의 두 개체를 비교합니다.

매개 변수에 고유한 IComparer 구현의 instance 제공하여 사용자 지정 비교를 comparer 지원할 수도 있습니다. 이 예제에서는 형식 인스턴스의 기본 정렬 순서를 반대로 하고 대/소문자를 구분하지 않는 문자열 비교를 수행하는 클래스를 정의 ReverseComparer 하여 이 작업을 수행합니다.

호출자 참고

.NET Framework 4 이전 버전에서는 빠른 정렬 알고리즘만 사용했습니다. Quicksort는 정렬 작업이 예외를 throw하고 호출자에게 예외를 throw IndexOutOfRangeException 하는 일부 상황에서 잘못된 비교자를 식별합니다 ArgumentException . .NET Framework 4.5부터는 삽입 정렬 및 힙소트 알고리즘이 잘못된 비교자를 검색하지 않으므로 이전에 던진 ArgumentException 정렬 작업에서 예외를 throw하지 않을 수 있습니다. 대부분의 경우 16개 요소보다 작거나 같은 배열에 적용됩니다.

추가 정보

적용 대상

Sort<T>(T[])

Array 에 있는 각 요소의 IComparable<T> 제네릭 인터페이스 구현을 사용하여 전체 Array의 요소를 정렬합니다.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array);
public static void Sort<T> (T[] array);
static member Sort : 'T[] -> unit
Public Shared Sub Sort(Of T) (array As T())

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

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

예외

array이(가) null인 경우

array의 요소 중 하나 이상이 IComparable<T> 제네릭 인터페이스를 구현하지 않는 경우

예제

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

배열이 표시되고 정렬되고 다시 표시됩니다.

참고

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

BinarySearch<T>(T[], T) 그런 다음, 제네릭 메서드 오버로드는 배열에 없는 문자열과 문자열을 검색하는 데 사용됩니다. 배열 및 메서드의 BinarySearch 반환 값은 제네릭 메서드에 ShowWhere 전달됩니다. 이 메서드는 문자열이 있으면 인덱스 값을 표시하고, 그렇지 않으면 검색 문자열이 배열에 있는 경우 사이에 있는 요소가 표시됩니다. 문자열이 n 배열이 아닌 경우 인덱스는 음수이므로 ShowWhere 메서드는 비트 보수(C#의 ~ 연산자 및 Visual C++의 Xor 경우 -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 각 요소는 의 IComparable<T> 다른 모든 요소와 비교할 수 있도록 제네릭 인터페이스를 array구현해야 합니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 입력 배열의 범위인 2 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 구성 알고리즘 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

추가 정보

적용 대상

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

지정한 Array 제네릭 인터페이스를 사용하여 IComparer<T> 의 요소를 정렬합니다.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array, System::Collections::Generic::IComparer<T> ^ comparer);
public static void Sort<T> (T[] array, System.Collections.Generic.IComparer<T> comparer);
public static void Sort<T> (T[] array, System.Collections.Generic.IComparer<T>? comparer);
static member Sort : 'T[] * System.Collections.Generic.IComparer<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), comparer As IComparer(Of T))

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

정렬할 1차원 0부터 시작 Array 합니다.

comparer
IComparer<T>

요소를 비교할 때 사용할 IComparer<T> 제네릭 인터페이스 구현이거나, 각 요소의 null 제네릭 인터페이스 구현을 사용할 경우 IComparable<T> 입니다.

예외

array이(가) null인 경우

comparernull이고, array 에 있는 하나 이상의 요소가 IComparable<T> 제네릭 인터페이스를 구현하지 않습니다.

comparer의 구현으로 인해 정렬 중에 오류가 발생했습니다. 예를 들어 항목을 자기 자신과 비교할 때 comparer에서 0을 반환하지 않을 수 있습니다.

예제

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

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

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

참고

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

BinarySearch<T>(T[], T, IComparer<T>) 그런 다음, 제네릭 메서드 오버로드는 배열에 없는 문자열과 문자열을 검색하는 데 사용됩니다. 배열 및 메서드의 BinarySearch<T>(T[], T, IComparer<T>) 반환 값은 제네릭 메서드에 ShowWhere 전달됩니다. 이 메서드는 문자열이 있으면 인덱스 값을 표시하고, 그렇지 않으면 검색 문자열이 배열에 있는 경우 사이에 있는 요소가 표시됩니다. 문자열이 n 배열이 아닌 경우 인덱스는 음수이므로 ShowWhere 메서드는 비트 보수(C#의 ~ 연산자 및 Visual C++의 Xor 경우 -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.

설명

가 이nullcomparerarray 각 요소는 의 다른 모든 요소array와 비교할 수 있도록 제네릭 인터페이스를 구현 IComparable<T> 해야 합니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 입력 배열의 범위인 2 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 구성 알고리즘 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

호출자 참고

.NET Framework 4 이전 버전에서는 빠른 구성 알고리즘만 사용했습니다. Quicksort는 정렬 작업이 예외를 throw하고 호출자에게 예외를 throw IndexOutOfRangeException 하는 일부 상황에서 잘못된 비교자를 식별합니다 ArgumentException . .NET Framework 4.5부터는 삽입 정렬 및 힙소트 알고리즘이 잘못된 비교자를 검색하지 않으므로 이전에 던진 ArgumentException 정렬 작업에서 예외가 throw되지 않을 수 있습니다. 대부분의 경우 16개 요소보다 작거나 같은 배열에 적용됩니다.

추가 정보

적용 대상

Sort<T>(T[], Comparison<T>)

지정한 Array 을 사용하여 Comparison<T>의 요소를 정렬합니다.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array, Comparison<T> ^ comparison);
public static void Sort<T> (T[] array, Comparison<T> comparison);
static member Sort : 'T[] * Comparison<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), comparison As Comparison(Of T))

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

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

comparison
Comparison<T>

요소를 비교할 때 사용할 Comparison<T>입니다.

예외

array이(가) null인 경우

또는

comparison이(가) null인 경우

comparison의 구현으로 인해 정렬 중에 오류가 발생했습니다. 예를 들어 항목을 자기 자신과 비교할 때 comparison에서 0을 반환하지 않을 수 있습니다.

예제

다음 코드 예제에서는 메서드 오버로드를 Sort(Comparison<T>) 보여 줍니다.

코드 예제에서는 라는 CompareDinosByLength문자열에 대한 대체 비교 메서드를 정의합니다. 이 메서드는 다음과 같이 작동합니다. 첫째, 비교가 테스트null되고 null 참조가 null이 아닌 참조보다 작게 처리됩니다. 둘째, 문자열 길이를 비교하고 긴 문자열은 더 큰 것으로 간주됩니다. 셋째, 길이가 같으면 일반 문자열 비교가 사용됩니다.

문자열 배열이 만들어지고 특정 순서 없이 4개의 문자열로 채워집니다. 목록에는 빈 문자열과 null 참조도 포함됩니다. 목록이 표시되고, 메서드를 나타내는 제네릭 대리자를 Comparison<T>CompareDinosByLength 사용하여 정렬되고, 다시 표시됩니다.

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

int CompareDinosByLength(String^ x, String^ y)
{
    if (x == nullptr)
    {
        if (y == nullptr)
        {
            // If x is null and y is null, they're
            // equal. 
            return 0;
        }
        else
        {
            // If x is null and y is not null, y
            // is greater. 
            return -1;
        }
    }
    else
    {
        // If x is not null...
        //
        if (y == nullptr)
            // ...and y is null, x is greater.
        {
            return 1;
        }
        else
        {
            // ...and y is not null, compare the 
            // lengths of the two strings.
            //
            int retval = x->Length.CompareTo(y->Length);

            if (retval != 0)
            {
                // If the strings are not of equal length,
                // the longer string is greater.
                //
                return retval;
            }
            else
            {
                // If the strings are of equal length,
                // sort them with ordinary string comparison.
                //
                return x->CompareTo(y);
            }
        }
    }
};

void Display(array<String^>^ arr)
{
    Console::WriteLine();
    for each(String^ s in arr)
    {
        if (s == nullptr)
            Console::WriteLine("(null)");
        else
            Console::WriteLine("\"{0}\"", s);
    }
};

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

    Console::WriteLine("\nSort with generic Comparison<String^> delegate:");
    Array::Sort(dinosaurs,
        gcnew Comparison<String^>(CompareDinosByLength));
    Display(dinosaurs);

}

/* This code example produces the following output:

"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"

Sort with generic Comparison<String^> delegate:

(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
 */
using System;
using System.Collections.Generic;

public class Example
{
    private static int CompareDinosByLength(string x, string y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're
                // equal.
                return 0;
            }
            else
            {
                // If x is null and y is not null, y
                // is greater.
                return -1;
            }
        }
        else
        {
            // If x is not null...
            //
            if (y == null)
                // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                // ...and y is not null, compare the
                // lengths of the two strings.
                //
                int retval = x.Length.CompareTo(y.Length);

                if (retval != 0)
                {
                    // If the strings are not of equal length,
                    // the longer string is greater.
                    //
                    return retval;
                }
                else
                {
                    // If the strings are of equal length,
                    // sort them with ordinary string comparison.
                    //
                    return x.CompareTo(y);
                }
            }
        }
    }

    public static void Main()
    {
        string[] dinosaurs = {
            "Pachycephalosaurus",
            "Amargasaurus",
            "",
            null,
            "Mamenchisaurus",
            "Deinonychus" };
        Display(dinosaurs);

        Console.WriteLine("\nSort with generic Comparison<string> delegate:");
        Array.Sort(dinosaurs, CompareDinosByLength);
        Display(dinosaurs);
    }

    private static void Display(string[] arr)
    {
        Console.WriteLine();
        foreach( string s in arr )
        {
            if (s == null)
                Console.WriteLine("(null)");
            else
                Console.WriteLine("\"{0}\"", s);
        }
    }
}

/* This code example produces the following output:

"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"

Sort with generic Comparison<string> delegate:

(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
 */
open System

let compareDinosByLength (x: string) (y: string) =
    match x with
    // If x is null and y is null, they're equal.
    | null when isNull y -> 0 
    // If x is null and y is not null, y is greater.
    | null -> -1
    // If x is not null and y is null, x is greater.
    | _ when isNull y -> 1    
    // If x is not null and y is not null, compare the lengths of the two strings.
    | _ ->
        let retval = x.Length.CompareTo y.Length
        if retval <> 0 then
            // If the strings are not of equal length, the longer string is greater.
            retval
        else
            // If the strings are of equal length, sort them with ordinary string comparison.
            x.CompareTo y

let display arr =
    printfn ""
    for s in arr do
        if isNull s then
            printfn "(null)"
        else
            printfn $"\"{s}\""

let dinosaurs =
    [| "Pachycephalosaurus"
       "Amargasaurus"
       ""
       null
       "Mamenchisaurus"
       "Deinonychus" |]
       
display dinosaurs

printfn "\nSort with generic Comparison<string> delegate:"
Array.Sort(dinosaurs, compareDinosByLength)
display dinosaurs

// This code example produces the following output:
//
//    "Pachycephalosaurus"
//    "Amargasaurus"
//    ""
//    (null)
//    "Mamenchisaurus"
//    "Deinonychus"
//    
//    Sort with generic Comparison<string> delegate:
//    
//    (null)
//    ""
//    "Deinonychus"
//    "Amargasaurus"
//    "Mamenchisaurus"
//    "Pachycephalosaurus"
//
Imports System.Collections.Generic

Public Class Example

    Private Shared Function CompareDinosByLength( _
        ByVal x As String, ByVal y As String) As Integer

        If x Is Nothing Then
            If y Is Nothing Then 
                ' If x is Nothing and y is Nothing, they're
                ' equal. 
                Return 0
            Else
                ' If x is Nothing and y is not Nothing, y
                ' is greater. 
                Return -1
            End If
        Else
            ' If x is not Nothing...
            '
            If y Is Nothing Then
                ' ...and y is Nothing, x is greater.
                Return 1
            Else
                ' ...and y is not Nothing, compare the 
                ' lengths of the two strings.
                '
                Dim retval As Integer = _
                    x.Length.CompareTo(y.Length)

                If retval <> 0 Then 
                    ' If the strings are not of equal length,
                    ' the longer string is greater.
                    '
                    Return retval
                Else
                    ' If the strings are of equal length,
                    ' sort them with ordinary string comparison.
                    '
                    Return x.CompareTo(y)
                End If
            End If
        End If

    End Function

    Public Shared Sub Main()

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

        Console.WriteLine(vbLf & "Sort with generic Comparison(Of String) delegate:")
        Array.Sort(dinosaurs, AddressOf CompareDinosByLength)
        Display(dinosaurs)

    End Sub

    Private Shared Sub Display(ByVal arr() As String)
        Console.WriteLine()
        For Each s As String In arr
            If s Is Nothing Then
                Console.WriteLine("(Nothing)")
            Else
                Console.WriteLine("""{0}""", s)
            End If
        Next
    End Sub
End Class

' This code example produces the following output:
'
'"Pachycephalosaurus"
'"Amargasaurus"
'""
'(Nothing)
'"Mamenchisaurus"
'"Deinonychus"
'
'Sort with generic Comparison(Of String) delegate:
'
'(Nothing)
'""
'"Deinonychus"
'"Amargasaurus"
'"Mamenchisaurus"
'"Pachycephalosaurus"

설명

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성적 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 입력 배열의 범위인 2 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 구성 알고리즘 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

호출자 참고

.NET Framework 4 이전 버전에서는 빠른 구성 알고리즘만 사용했습니다. Quicksort는 정렬 작업이 예외를 throw하고 호출자에게 예외를 throw IndexOutOfRangeException 하는 일부 상황에서 잘못된 비교자를 식별합니다 ArgumentException . .NET Framework 4.5부터는 삽입 정렬 및 힙소트 알고리즘이 잘못된 비교자를 검색하지 않으므로 이전에 던진 ArgumentException 정렬 작업에서 예외가 throw되지 않을 수 있습니다. 대부분의 경우 6개 요소보다 작거나 같은 배열에 적용됩니다.

추가 정보

적용 대상

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

Array 에 있는 각 요소의 IComparable<T> 제네릭 인터페이스 구현을 사용하여 Array의 요소 범위에 있는 요소를 정렬합니다.

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

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

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

index
Int32

정렬할 범위의 시작 인덱스입니다.

length
Int32

정렬할 범위에 있는 요소 수입니다.

예외

array이(가) null인 경우

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

또는

length가 0보다 작은 경우

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

array의 요소 중 하나 이상이 IComparable<T> 제네릭 인터페이스를 구현하지 않는 경우

예제

다음 코드 예제에서는 배열의 Sort<T>(T[], Int32, Int32) 범위를 정렬하기 위한 제네릭 메서드 오버로드 및 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 제네릭 메서드 오버로드를 보여 줍니다.

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

이 코드 예제에서는 세 개의 초식동물과 세 마리의 육식 동물(정확하게 말하자면 티라노사우리드)로 구성된 공룡 이름의 배열을 만들고 표시합니다. Sort<T>(T[], Int32, Int32) 제네릭 메서드 오버로드는 배열의 마지막 세 요소를 정렬하는 데 사용되며, 그런 다음 표시됩니다. Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 제네릭 메서드 오버로드는 와 함께 ReverseCompare 사용하여 마지막 세 요소를 역순으로 정렬합니다. 철저하게 혼란스러운 공룡이 다시 표시됩니다.

참고

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

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);
    }
};

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
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",
                              "Mamenchisaurus",
                              "Tarbosaurus",
                              "Tyrannosaurus",
                              "Albertasaurus"};

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface  IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs = 
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Tarbosaurus"
       "Tyrannosaurus"
       "Albertasaurus" |]

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

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

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

let rc = ReverseComparer()

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

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


// This code example produces the following output:
//
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Tarbosaurus
//    Tyrannosaurus
//    Albertasaurus
//    
//    Sort(dinosaurs, 3, 3)
//    
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Albertasaurus
//    Tarbosaurus
//    Tyrannosaurus
//    
//    Sort(dinosaurs, 3, 3, rc)
//    
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Tyrannosaurus
//    Tarbosaurus
//    Albertasaurus
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", _
            "Mamenchisaurus", _
            "Tarbosaurus", _
            "Tyrannosaurus", _
            "Albertasaurus"  }

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

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

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

        Dim rc As New ReverseComparer()

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

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

    End Sub

End Class

' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Tarbosaurus
'Tyrannosaurus
'Albertasaurus
'
'Sort(dinosaurs, 3, 3)
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Albertasaurus
'Tarbosaurus
'Tyrannosaurus
'
'Sort(dinosaurs, 3, 3, rc)
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Tyrannosaurus
'Tarbosaurus
'Albertasaurus

설명

의 지정된 요소 범위 내의 각 요소는 의 다른 모든 요소 arrayarray와 비교할 수 있도록 제네릭 인터페이스를 구현 IComparable<T> 해야 합니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 입력 배열의 범위인 2 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 구성 알고리즘 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

추가 정보

적용 대상

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

지정한 Array 제네릭 인터페이스를 사용하여 IComparer<T> 의 요소 범위에 있는 요소를 정렬합니다.

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

형식 매개 변수

T

배열 요소의 형식입니다.

매개 변수

array
T[]

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

index
Int32

정렬할 범위의 시작 인덱스입니다.

length
Int32

정렬할 범위에 있는 요소 수입니다.

comparer
IComparer<T>

요소를 비교할 때 사용할 IComparer<T> 제네릭 인터페이스 구현이거나, 각 요소의 null 제네릭 인터페이스 구현을 사용할 경우 IComparable<T> 입니다.

예외

array이(가) null인 경우

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

또는

length가 0보다 작은 경우

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

또는

comparer의 구현으로 인해 정렬 중에 오류가 발생했습니다. 예를 들어 항목을 자기 자신과 비교할 때 comparer에서 0을 반환하지 않을 수 있습니다.

comparernull이고, array 에 있는 하나 이상의 요소가 IComparable<T> 제네릭 인터페이스를 구현하지 않습니다.

예제

다음 코드 예제에서는 배열의 Sort<T>(T[], Int32, Int32) 범위를 정렬하기 위한 제네릭 메서드 오버로드 및 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 제네릭 메서드 오버로드를 보여 줍니다.

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

이 코드 예제에서는 세 개의 초식동물과 세 마리의 육식 동물(정확하게 말하자면 티라노사우리드)로 구성된 공룡 이름의 배열을 만들고 표시합니다. Sort<T>(T[], Int32, Int32) 제네릭 메서드 오버로드는 배열의 마지막 세 요소를 정렬하는 데 사용되며, 그런 다음 표시됩니다. Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 제네릭 메서드 오버로드는 와 함께 ReverseCompare 사용하여 마지막 세 요소를 역순으로 정렬합니다. 철저하게 혼란스러운 공룡이 다시 표시됩니다.

참고

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

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);
    }
};

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
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",
                              "Mamenchisaurus",
                              "Tarbosaurus",
                              "Tyrannosaurus",
                              "Albertasaurus"};

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface  IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs = 
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Tarbosaurus"
       "Tyrannosaurus"
       "Albertasaurus" |]

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

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

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

let rc = ReverseComparer()

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

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


// This code example produces the following output:
//
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Tarbosaurus
//    Tyrannosaurus
//    Albertasaurus
//    
//    Sort(dinosaurs, 3, 3)
//    
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Albertasaurus
//    Tarbosaurus
//    Tyrannosaurus
//    
//    Sort(dinosaurs, 3, 3, rc)
//    
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Tyrannosaurus
//    Tarbosaurus
//    Albertasaurus
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", _
            "Mamenchisaurus", _
            "Tarbosaurus", _
            "Tyrannosaurus", _
            "Albertasaurus"  }

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

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

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

        Dim rc As New ReverseComparer()

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

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

    End Sub

End Class

' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Tarbosaurus
'Tyrannosaurus
'Albertasaurus
'
'Sort(dinosaurs, 3, 3)
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Albertasaurus
'Tarbosaurus
'Tyrannosaurus
'
'Sort(dinosaurs, 3, 3, rc)
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Tyrannosaurus
'Tarbosaurus
'Albertasaurus

설명

가 이nullcomparer 의 지정된 요소 범위 내의 각 요소는 의 다른 모든 요소 arrayarray 와 비교할 수 있도록 제네릭 인터페이스를 구현 IComparable<T> 해야 합니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 입력 배열의 범위인 2 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 구성 알고리즘 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

호출자 참고

.NET Framework 4 이전 버전에서는 빠른 구성 알고리즘만 사용했습니다. Quicksort는 정렬 작업이 예외를 throw하고 호출자에게 예외를 throw IndexOutOfRangeException 하는 일부 상황에서 잘못된 비교자를 식별합니다 ArgumentException . .NET Framework 4.5부터는 삽입 정렬 및 힙소트 알고리즘이 잘못된 비교자를 검색하지 않으므로 이전에 던진 ArgumentException 정렬 작업에서 예외가 throw되지 않을 수 있습니다. 대부분의 경우 16개 요소보다 작거나 같은 배열에 적용됩니다.

추가 정보

적용 대상

Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)

지정한 Array 제네릭 인터페이스를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 IComparer<T> 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)의 요소 범위를 정렬합니다.

public:
generic <typename TKey, typename TValue>
 static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items, int index, int length, System::Collections::Generic::IComparer<TKey> ^ comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items, int index, int length, System.Collections.Generic.IComparer<TKey>? comparer);
static member Sort : 'Key[] * 'Value[] * int * int * System.Collections.Generic.IComparer<'Key> -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue(), index As Integer, length As Integer, comparer As IComparer(Of TKey))

형식 매개 변수

TKey

키 배열 요소의 형식입니다.

TValue

항목 배열 요소의 형식입니다.

매개 변수

keys
TKey[]

정렬할 키를 포함하는 1차원 Array (인덱스는 0부터 시작)입니다.

items
TValue[]

keys의 키에 해당하는 항목을 포함하는 1차원 Array(인덱스는 0부터 시작)이거나 keys만 정렬할 경우 null입니다.

index
Int32

정렬할 범위의 시작 인덱스입니다.

length
Int32

정렬할 범위에 있는 요소 수입니다.

comparer
IComparer<TKey>

요소를 비교할 때 사용할 IComparer<T> 제네릭 인터페이스 구현이거나, 각 요소의 null 제네릭 인터페이스 구현을 사용할 경우 IComparable<T> 입니다.

예외

keys이(가) null인 경우

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

또는

length가 0보다 작은 경우

itemsnull이 아니고 keys 의 하한 범위가 items의 하한 범위와 일치하지 않습니다.

또는

itemsnull이 아니고 keys 의 길이가 items의 길이보다 큽니다.

또는

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

또는

itemsnull이 아니고 indexlengthitemsArray의 올바른 범위를 지정하지 않습니다.

또는

comparer의 구현으로 인해 정렬 중에 오류가 발생했습니다. 예를 들어 항목을 자기 자신과 비교할 때 comparer에서 0을 반환하지 않을 수 있습니다.

comparernull이고, keysArray 의 하나 이상의 요소가 IComparable<T> 제네릭 인터페이스를 구현하지 않습니다.

예제

다음 코드 예제에서는 키와 값을 나타내는 배열 쌍을 정렬하기 위한 , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 제네릭 메서드 오버로드를 보여 Sort<TKey,TValue>(TKey[], TValue[])줍니다.

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

이 코드 예제에서는 공룡 이름(키) 배열과 각 공룡의 최대 길이를 미터(값)로 나타내는 정수 배열을 만들고 표시합니다. 그런 다음 배열이 정렬되고 여러 번 표시됩니다.

참고

Visual Basic, C#및 C++는 처음 두 인수의 형식에서 제네릭 형식 매개 변수의 형식을 유추하기 때문에 제네릭 메서드에 대한 호출은 제네릭이 아닌 메서드에 대한 호출과 다르지 않습니다. Ildasm.exe(IL 디스어셈블러)를 사용하여 MSIL(Microsoft Intermediate Language)을 검사하는 경우 제네릭 메서드가 호출되고 있음을 확인할 수 있습니다.

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);
    }
};

void main()
{
    array<String^>^ dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

    array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
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 = {
            "Seismosaurus",
            "Chasmosaurus",
            "Coelophysis",
            "Mamenchisaurus",
            "Caudipteryx",
            "Cetiosaurus"  };

        int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

        ReverseComparer rc = new ReverseComparer();

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs =
    [| "Seismosaurus"
       "Chasmosaurus"
       "Coelophysis"
       "Mamenchisaurus"
       "Caudipteryx"
       "Cetiosaurus" |]

let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

let rc = ReverseComparer()

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

// This code example produces the following output:
//
//    Seismosaurus: up to 40 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Coelophysis: up to 3 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes)
//    
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Coelophysis: up to 3 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Seismosaurus: up to 40 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, rc)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Caudipteryx: up to 1 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, 3, 3)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Chasmosaurus: up to 5 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Caudipteryx: up to 1 meters long.
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 = { _
            "Seismosaurus", _
            "Chasmosaurus", _
            "Coelophysis", _
            "Mamenchisaurus", _
            "Caudipteryx", _
            "Cetiosaurus"  }

        Dim dinosaurSizes() As Integer = { 40, 5, 3, 22, 1, 18 }

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

        Dim rc As New ReverseComparer()

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

        Console.WriteLine(vbLf & _
            "Sort(dinosaurs, dinosaurSizes, 3, 3)")
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

    End Sub

End Class

' This code example produces the following output:
'
'Seismosaurus: up to 40 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'
'Sort(dinosaurs, dinosaurSizes)
'
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Seismosaurus: up to 40 meters long.
'
'Sort(dinosaurs, dinosaurSizes, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.

설명

keysArray 각 키에는 에 해당 항목이 itemsArray있습니다. 정렬하는 동안 키의 위치가 변경되면 의 해당 항목 itemsArray 의 위치도 비슷하게 변경됩니다. 따라서 는 itemsArray 에서 해당 키의 정렬에 따라 정렬됩니다 keysArray.

가 이nullcomparer 의 지정된 요소 범위 내의 각 키는 keysArray 다른 모든 키와 비교할 수 있도록 제네릭 인터페이스를 구현 IComparable<T> 해야 합니다.

키보다 많은 항목이 있는 경우 정렬할 수 있지만 해당 키가 없는 항목은 정렬되지 않습니다. 항목보다 더 많은 키가 있는 경우 정렬할 수 없습니다. 이렇게 하면 가 ArgumentExceptionthrow됩니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 입력 배열의 범위인 2 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 구성 알고리즘 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

호출자 참고

.NET Framework 4 이전 버전에서는 빠른 구성 알고리즘만 사용했습니다. Quicksort는 정렬 작업이 예외를 throw하고 호출자에게 예외를 throw IndexOutOfRangeException 하는 일부 상황에서 잘못된 비교자를 식별합니다 ArgumentException . .NET Framework 4.5부터는 삽입 정렬 및 힙소트 알고리즘이 잘못된 비교자를 검색하지 않으므로 이전에 던진 ArgumentException 정렬 작업에서 예외가 throw되지 않을 수 있습니다. 대부분의 경우 16개 요소보다 작거나 같은 배열에 적용됩니다.

추가 정보

적용 대상

Sort<TKey,TValue>(TKey[], TValue[])

각 키의 Array 제네릭 인터페이스 구현을 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 IComparable<T> 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)를 정렬합니다.

public:
generic <typename TKey, typename TValue>
 static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items);
static member Sort : 'Key[] * 'Value[] -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue())

형식 매개 변수

TKey

키 배열 요소의 형식입니다.

TValue

항목 배열 요소의 형식입니다.

매개 변수

keys
TKey[]

정렬할 키를 포함하는 1차원 Array (인덱스는 0부터 시작)입니다.

items
TValue[]

keys의 키에 해당하는 항목을 포함하는 1차원 Array(인덱스는 0부터 시작)이거나 keys만 정렬할 경우 null입니다.

예외

keys이(가) null인 경우

itemsnull이 아니고 keys 의 하한 범위가 items의 하한 범위와 일치하지 않습니다.

또는

itemsnull이 아니고 keys 의 길이가 items의 길이보다 큽니다.

keysArray의 요소 중 하나 이상이 IComparable<T> 제네릭 인터페이스를 구현하지 않는 경우

예제

다음 코드 예제에서는 키와 값을 나타내는 배열 쌍을 정렬하기 위한 , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 제네릭 메서드 오버로드를 보여 Sort<TKey,TValue>(TKey[], TValue[])줍니다.

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

이 코드 예제에서는 공룡 이름(키) 배열과 각 공룡의 최대 길이를 미터(값)로 나타내는 정수 배열을 만들고 표시합니다. 그런 다음 배열이 정렬되고 여러 번 표시됩니다.

참고

Visual Basic, C#및 C++는 처음 두 인수의 형식에서 제네릭 형식 매개 변수의 형식을 유추하기 때문에 제네릭 메서드에 대한 호출은 제네릭이 아닌 메서드에 대한 호출과 다르지 않습니다. Ildasm.exe(IL 디스어셈블러)를 사용하여 MSIL(Microsoft Intermediate Language)을 검사하는 경우 제네릭 메서드가 호출되고 있음을 확인할 수 있습니다.

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);
    }
};

void main()
{
    array<String^>^ dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

    array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
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 = {
            "Seismosaurus",
            "Chasmosaurus",
            "Coelophysis",
            "Mamenchisaurus",
            "Caudipteryx",
            "Cetiosaurus"  };

        int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

        ReverseComparer rc = new ReverseComparer();

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs =
    [| "Seismosaurus"
       "Chasmosaurus"
       "Coelophysis"
       "Mamenchisaurus"
       "Caudipteryx"
       "Cetiosaurus" |]

let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

let rc = ReverseComparer()

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

// This code example produces the following output:
//
//    Seismosaurus: up to 40 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Coelophysis: up to 3 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes)
//    
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Coelophysis: up to 3 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Seismosaurus: up to 40 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, rc)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Caudipteryx: up to 1 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, 3, 3)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Chasmosaurus: up to 5 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Caudipteryx: up to 1 meters long.
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 = { _
            "Seismosaurus", _
            "Chasmosaurus", _
            "Coelophysis", _
            "Mamenchisaurus", _
            "Caudipteryx", _
            "Cetiosaurus"  }

        Dim dinosaurSizes() As Integer = { 40, 5, 3, 22, 1, 18 }

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

        Dim rc As New ReverseComparer()

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

        Console.WriteLine(vbLf & _
            "Sort(dinosaurs, dinosaurSizes, 3, 3)")
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

    End Sub

End Class

' This code example produces the following output:
'
'Seismosaurus: up to 40 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'
'Sort(dinosaurs, dinosaurSizes)
'
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Seismosaurus: up to 40 meters long.
'
'Sort(dinosaurs, dinosaurSizes, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.

설명

keysArray 각 키에는 에 해당 항목이 itemsArray있습니다. 정렬하는 동안 키의 위치가 변경되면 의 해당 항목 itemsArray 의 위치도 비슷하게 변경됩니다. 따라서 는 itemsArray 에서 해당 키의 정렬에 따라 정렬됩니다 keysArray.

의 각 키는 keysArray 다른 모든 키와 비교할 수 있도록 제네릭 인터페이스를 구현 IComparable<T> 해야 합니다.

키보다 많은 항목이 있는 경우 정렬할 수 있지만 해당 키가 없는 항목은 정렬되지 않습니다. 항목보다 더 많은 키가 있는 경우 정렬할 수 없습니다. 이렇게 하면 가 ArgumentExceptionthrow됩니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 입력 배열의 범위인 2 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 구성 알고리즘 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

추가 정보

적용 대상

Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)

지정한 Array 제네릭 인터페이스를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 IComparer<T> 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)를 정렬합니다.

public:
generic <typename TKey, typename TValue>
 static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items, System::Collections::Generic::IComparer<TKey> ^ comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items, System.Collections.Generic.IComparer<TKey>? comparer);
static member Sort : 'Key[] * 'Value[] * System.Collections.Generic.IComparer<'Key> -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue(), comparer As IComparer(Of TKey))

형식 매개 변수

TKey

키 배열 요소의 형식입니다.

TValue

항목 배열 요소의 형식입니다.

매개 변수

keys
TKey[]

정렬할 키를 포함하는 1차원 Array (인덱스는 0부터 시작)입니다.

items
TValue[]

keys의 키에 해당하는 항목을 포함하는 1차원 Array(인덱스는 0부터 시작)이거나 keys만 정렬할 경우 null입니다.

comparer
IComparer<TKey>

요소를 비교할 때 사용할 IComparer<T> 제네릭 인터페이스 구현이거나, 각 요소의 null 제네릭 인터페이스 구현을 사용할 경우 IComparable<T> 입니다.

예외

keys이(가) null인 경우

itemsnull이 아니고 keys 의 하한 범위가 items의 하한 범위와 일치하지 않습니다.

또는

itemsnull이 아니고 keys 의 길이가 items의 길이보다 큽니다.

또는

comparer의 구현으로 인해 정렬 중에 오류가 발생했습니다. 예를 들어 항목을 자기 자신과 비교할 때 comparer에서 0을 반환하지 않을 수 있습니다.

comparernull이고, keysArray 의 하나 이상의 요소가 IComparable<T> 제네릭 인터페이스를 구현하지 않습니다.

예제

다음 코드 예제에서는 키와 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 값을 나타내는 배열 쌍을 정렬하기 위한 , [], Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)및 제네릭 메서드 오버로드를 보여 Sort<TKey,TValue>(TKey[], TValue[])줍니다.

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

이 코드 예제에서는 공룡 이름(키) 배열과 각 공룡의 최대 길이를 미터(값)로 나타내는 정수 배열을 만들고 표시합니다. 그런 다음 배열이 정렬되고 여러 번 표시됩니다.

참고

Visual Basic, C#및 C++는 처음 두 인수의 형식에서 제네릭 형식 매개 변수의 형식을 유추하기 때문에 제네릭 메서드에 대한 호출은 제네릭이 아닌 메서드에 대한 호출과 다르지 않습니다. Ildasm.exe(IL 디스어셈블러)를 사용하여 MSIL(Microsoft Intermediate Language)을 검사하는 경우 제네릭 메서드가 호출되고 있음을 확인할 수 있습니다.

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);
    }
};

void main()
{
    array<String^>^ dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

    array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
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 = {
            "Seismosaurus",
            "Chasmosaurus",
            "Coelophysis",
            "Mamenchisaurus",
            "Caudipteryx",
            "Cetiosaurus"  };

        int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

        ReverseComparer rc = new ReverseComparer();

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs =
    [| "Seismosaurus"
       "Chasmosaurus"
       "Coelophysis"
       "Mamenchisaurus"
       "Caudipteryx"
       "Cetiosaurus" |]

let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

let rc = ReverseComparer()

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

// This code example produces the following output:
//
//    Seismosaurus: up to 40 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Coelophysis: up to 3 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes)
//    
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Coelophysis: up to 3 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Seismosaurus: up to 40 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, rc)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Caudipteryx: up to 1 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, 3, 3)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Chasmosaurus: up to 5 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Caudipteryx: up to 1 meters long.
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 = { _
            "Seismosaurus", _
            "Chasmosaurus", _
            "Coelophysis", _
            "Mamenchisaurus", _
            "Caudipteryx", _
            "Cetiosaurus"  }

        Dim dinosaurSizes() As Integer = { 40, 5, 3, 22, 1, 18 }

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

        Dim rc As New ReverseComparer()

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

        Console.WriteLine(vbLf & _
            "Sort(dinosaurs, dinosaurSizes, 3, 3)")
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

    End Sub

End Class

' This code example produces the following output:
'
'Seismosaurus: up to 40 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'
'Sort(dinosaurs, dinosaurSizes)
'
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Seismosaurus: up to 40 meters long.
'
'Sort(dinosaurs, dinosaurSizes, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.

설명

keysArray 각 키에는 에 해당 항목이 itemsArray있습니다. 정렬하는 동안 키의 위치가 변경되면 의 해당 항목 itemsArray 의 위치도 비슷하게 변경됩니다. 따라서 는 itemsArray 에서 해당 키의 정렬에 따라 정렬됩니다 keysArray.

가 이nullcomparerkeysArray 각 키는 다른 모든 키와 비교할 수 있도록 제네릭 인터페이스를 구현 IComparable<T> 해야 합니다.

키보다 더 많은 항목이 있는 경우 정렬할 수 있지만 해당 키가 없는 항목은 정렬되지 않습니다. 항목보다 키가 더 많은 경우 정렬할 수 없습니다. 이렇게 하면 가 ArgumentExceptionthrow됩니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 2 * LogN을 초과하는 경우 여기서 N 은 입력 배열의 범위이며 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 정렬 알고리즘을 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

호출자 참고

.NET Framework 4 이전 버전에서는 빠른 구성 알고리즘만 사용했습니다. Quicksort는 정렬 작업이 예외를 throw하고 호출자에게 예외를 throw IndexOutOfRangeException 하는 일부 상황에서 잘못된 비교자를 식별합니다 ArgumentException . .NET Framework 4.5부터는 삽입 정렬 및 힙소트 알고리즘이 잘못된 비교자를 검색하지 않으므로 이전에 던진 ArgumentException 정렬 작업에서 예외가 throw되지 않을 수 있습니다. 대부분의 경우 16개 요소보다 작거나 같은 배열에 적용됩니다.

추가 정보

적용 대상

Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)

각 키에서 구현하는 Array 제네릭 인터페이스를 사용하여 첫 번째 Array 에 있는 키를 기반으로 하는 한 쌍의 IComparable<T> 개체(키를 포함하는 개체와 해당 항목을 포함하는 개체)의 요소 범위를 정렬합니다.

public:
generic <typename TKey, typename TValue>
 static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items, int index, int length);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, int index, int length);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items, int index, int length);
static member Sort : 'Key[] * 'Value[] * int * int -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue(), index As Integer, length As Integer)

형식 매개 변수

TKey

키 배열 요소의 형식입니다.

TValue

항목 배열 요소의 형식입니다.

매개 변수

keys
TKey[]

정렬할 키를 포함하는 1차원 Array (인덱스는 0부터 시작)입니다.

items
TValue[]

keys의 키에 해당하는 항목을 포함하는 1차원 Array(인덱스는 0부터 시작)이거나 keys만 정렬할 경우 null입니다.

index
Int32

정렬할 범위의 시작 인덱스입니다.

length
Int32

정렬할 범위에 있는 요소 수입니다.

예외

keys이(가) null인 경우

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

또는

length가 0보다 작은 경우

itemsnull이 아니고 keys 의 하한 범위가 items의 하한 범위와 일치하지 않습니다.

또는

itemsnull이 아니고 keys 의 길이가 items의 길이보다 큽니다.

또는

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

또는

itemsnull이 아니고 indexlengthitemsArray의 올바른 범위를 지정하지 않습니다.

keysArray의 요소 중 하나 이상이 IComparable<T> 제네릭 인터페이스를 구현하지 않는 경우

예제

다음 코드 예제에서는 키와 값을 나타내는 배열 쌍을 정렬하기 위한 , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 제네릭 메서드 오버로드를 보여 Sort<TKey,TValue>(TKey[], TValue[])줍니다.

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

이 코드 예제에서는 공룡 이름(키) 배열과 각 공룡의 최대 길이(미터)를 나타내는 정수 배열을 만들고 표시합니다. 그런 다음 배열이 정렬되고 여러 번 표시됩니다.

참고

Visual Basic, C#및 C++는 처음 두 인수의 형식에서 제네릭 형식 매개 변수의 형식을 유추하기 때문에 제네릭 메서드에 대한 호출은 제네릭이 아닌 메서드에 대한 호출과 다르지 않습니다. Ildasm.exe(IL 디스어셈블러)를 사용하여 MSIL(Microsoft Intermediate Language)을 검사하는 경우 제네릭 메서드가 호출되고 있음을 확인할 수 있습니다.

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);
    }
};

void main()
{
    array<String^>^ dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

    array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

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

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
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 = {
            "Seismosaurus",
            "Chasmosaurus",
            "Coelophysis",
            "Mamenchisaurus",
            "Caudipteryx",
            "Cetiosaurus"  };

        int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

        ReverseComparer rc = new ReverseComparer();

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }

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

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.",
                dinosaurs[i], dinosaurSizes[i]);
        }
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs =
    [| "Seismosaurus"
       "Chasmosaurus"
       "Coelophysis"
       "Mamenchisaurus"
       "Caudipteryx"
       "Cetiosaurus" |]

let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

let rc = ReverseComparer()

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

// This code example produces the following output:
//
//    Seismosaurus: up to 40 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Coelophysis: up to 3 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes)
//    
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Coelophysis: up to 3 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Seismosaurus: up to 40 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, rc)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Caudipteryx: up to 1 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, 3, 3)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Caudipteryx: up to 1 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Chasmosaurus: up to 5 meters long.
//    
//    Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
//    
//    Seismosaurus: up to 40 meters long.
//    Mamenchisaurus: up to 22 meters long.
//    Coelophysis: up to 3 meters long.
//    Chasmosaurus: up to 5 meters long.
//    Cetiosaurus: up to 18 meters long.
//    Caudipteryx: up to 1 meters long.
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 = { _
            "Seismosaurus", _
            "Chasmosaurus", _
            "Coelophysis", _
            "Mamenchisaurus", _
            "Caudipteryx", _
            "Cetiosaurus"  }

        Dim dinosaurSizes() As Integer = { 40, 5, 3, 22, 1, 18 }

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

        Dim rc As New ReverseComparer()

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

        Console.WriteLine(vbLf & _
            "Sort(dinosaurs, dinosaurSizes, 3, 3)")
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

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

        Console.WriteLine()
        For i As Integer = 0 To dinosaurs.Length - 1
            Console.WriteLine("{0}: up to {1} meters long.", _
                dinosaurs(i), dinosaurSizes(i))
        Next

    End Sub

End Class

' This code example produces the following output:
'
'Seismosaurus: up to 40 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'
'Sort(dinosaurs, dinosaurSizes)
'
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Seismosaurus: up to 40 meters long.
'
'Sort(dinosaurs, dinosaurSizes, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.

설명

keysArray 각 키에는 에 해당 항목이 itemsArray있습니다. 정렬하는 동안 키의 위치가 변경되면 의 해당 항목 itemsArray 의 위치도 비슷하게 변경됩니다. 따라서 는 itemsArray 에서 해당 키의 정렬에 따라 정렬됩니다 keysArray.

의 지정된 요소 keysArray 범위 내의 각 키는 다른 모든 키와 비교할 수 있도록 제네릭 인터페이스를 구현 IComparable<T> 해야 합니다.

키보다 더 많은 항목이 있는 경우 정렬할 수 있지만 해당 키가 없는 항목은 정렬되지 않습니다. 항목보다 키가 더 많은 경우 정렬할 수 없습니다. 이렇게 하면 가 ArgumentExceptionthrow됩니다.

정렬이 성공적으로 완료되지 않으면 결과가 정의되지 않습니다.

이 메서드는 다음과 같이 내성 정렬(introsort) 알고리즘을 사용합니다.

  • 파티션 크기가 16개 요소보다 작거나 같은 경우 삽입 정렬 알고리즘을 사용합니다.

  • 파티션 수가 2 * LogN을 초과하는 경우 여기서 N 은 입력 배열의 범위이며 힙소트 알고리즘을 사용합니다.

  • 그렇지 않으면 빠른 정렬 알고리즘을 사용합니다.

이 구현은 불안정한 정렬을 수행합니다. 즉, 두 요소가 같으면 순서가 유지되지 않을 수 있습니다. 반면, 안정적인 정렬은 같은 요소의 순서를 유지합니다.

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

추가 정보

적용 대상