Array.Sort 메서드

정의

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

오버로드

Name Description
Sort(Array, Array, Int32, Int32, IComparer)

지정된 IComparer개체를 사용하여 첫 번째 Array 키에 따라 1차원 Array 개체 쌍의 요소 범위를 정렬합니다(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함).

Sort(Array, Int32, Int32, IComparer)

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

Sort(Array, Array, Int32, Int32)

각 키의 구현을 사용하여 IComparable 첫 번째 Array 키에 따라 1차원 Array 개체 쌍의 요소 범위를 정렬합니다(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함).

Sort(Array, Int32, Int32)

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

Sort(Array, Array, IComparer)

지정된 IComparer키를 사용하여 첫 번째 Array 키에 따라 1차원 Array 개체 쌍(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함)을 정렬합니다.

Sort(Array, Array)

각 키의 구현을 사용하여 IComparable 첫 번째 Array 키에 따라 1차원 Array 개체 쌍(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함)을 정렬합니다.

Sort(Array)

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

Sort(Array, IComparer)

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

Sort<T>(T[])

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

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

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

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

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

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

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

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

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

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

지정된 IComparer<T> 제네릭 인터페이스를 사용하여 첫 번째 Array 키에 따라 개체 쌍의 Array 요소 범위를 정렬합니다(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함).

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

각 키의 Array 제네릭 인터페이스 구현을 사용하여 IComparable<T> 첫 번째 Array 키에 따라 개체 쌍(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함)을 정렬합니다.

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

지정된 IComparer<T> 제네릭 인터페이스를 사용하여 첫 번째 Array 키에 따라 개체 쌍Array(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함)을 정렬합니다.

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

각 키의 제네릭 인터페이스 구현을 사용하여 IComparable<T> 첫 번째 Array 키에 따라 개체 쌍의 Array 요소 범위를 정렬합니다(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함).

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

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

지정된 IComparer개체를 사용하여 첫 번째 Array 키에 따라 1차원 Array 개체 쌍의 요소 범위를 정렬합니다(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함).

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

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

-또는-

null 에서만 정렬합니다 keysArray.

index
Int32

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

length
Int32

정렬할 범위의 요소 수입니다.

comparer
IComparer

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

-또는-

각 요소의 구현을 사용하려면 />입니다.

예외

keysnull입니다.

keys Array 다차원입니다.

-또는-

items Array 다차원입니다.

index 가 .의 keys하한보다 작습니다.

-또는-

length가 0보다 작습니다.

items 가 아니 null고 하한이 .의 keys 하한 items과 일치하지 않습니다.

-또는-

items 가 아니 null고 길이가 .의 keysitems길이보다 큽다.

-또는-

indexlength 유효한 범위를 keysArray지정하지 마세요.

-또는-

items 가 아닌 null경우 . indexlengthitemsArray유효한 범위를 지정하지 않습니다.

-또는-

정렬 중에 comparer 오류가 발생했습니다. 예를 들어 comparer 항목 자체를 비교할 때 0을 반환하지 않을 수 있습니다.

comparernull있고 인터페이스를 구현 IComparable 하지 않는 요소 중 하나 이상 keysArray 입니다.

예제

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

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.

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

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

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

.NET 다음 표에 나열된 미리 정의된 IComparer 구현을 포함합니다.

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

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

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

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

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

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

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

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

호출자 참고

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

추가 정보

적용 대상

Sort(Array, Int32, Int32, IComparer)

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

지정된 요소를 사용하여 1차원 Array 요소 범위의 요소를 정렬합니다 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 요소를 비교할 때 사용할 구현입니다.

-또는-

각 요소의 구현을 사용하려면 />입니다.

예외

arraynull입니다.

array 가 다차원입니다.

index 가 .의 array하한보다 작습니다.

-또는-

length가 0보다 작습니다.

index 에서 length 유효한 범위를 array지정하지 않습니다.

-또는-

정렬 중에 comparer 오류가 발생했습니다. 예를 들어 comparer 항목 자체를 비교할 때 0을 반환하지 않을 수 있습니다.

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

예제

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

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

설명

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

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

.NET 다음 표에 나열된 미리 정의된 IComparer 구현을 포함합니다.

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

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

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

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

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

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

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

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

호출자 참고

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

추가 정보

적용 대상

Sort(Array, Array, Int32, Int32)

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

각 키의 구현을 사용하여 IComparable 첫 번째 Array 키에 따라 1차원 Array 개체 쌍의 요소 범위를 정렬합니다(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함).

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

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

-또는-

null 에서만 정렬합니다 keysArray.

index
Int32

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

length
Int32

정렬할 범위의 요소 수입니다.

예외

keysnull입니다.

keys Array 다차원입니다.

-또는-

items Array 다차원입니다.

index 가 .의 keys하한보다 작습니다.

-또는-

length가 0보다 작습니다.

items 가 아니 null고 길이가 .의 keysitems길이보다 큽다.

-또는-

indexlength 유효한 범위를 keysArray지정하지 마세요.

-또는-

items 가 아닌 null경우 . indexlengthitemsArray유효한 범위를 지정하지 않습니다.

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

예제

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

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 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

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

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

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

추가 정보

적용 대상

Sort(Array, Int32, Int32)

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

각 요소의 구현을 사용하여 IComparable 1차원 Array 요소 범위의 요소를 정렬합니다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

정렬할 범위의 요소 수입니다.

예외

arraynull입니다.

array 가 다차원입니다.

index 가 .의 array하한보다 작습니다.

-또는-

length가 0보다 작습니다.

index 에서 length 유효한 범위를 array지정하지 않습니다.

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

예제

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

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 범위 내의 각 요소는 인터페이스를 IComparable 구현하여 다른 모든 요소 array와 비교할 수 있어야 합니다.

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

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

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

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

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

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

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

추가 정보

적용 대상

Sort(Array, Array, IComparer)

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

지정된 IComparer키를 사용하여 첫 번째 Array 키에 따라 1차원 Array 개체 쌍(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함)을 정렬합니다.

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

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

-또는-

null 에서만 정렬합니다 keysArray.

comparer
IComparer

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

-또는-

각 요소의 구현을 사용하려면 />입니다.

예외

keysnull입니다.

keys Array 다차원입니다.

-또는-

items Array 다차원입니다.

items 가 아니 null고 길이가 .의 keysitems길이보다 큽다.

-또는-

정렬 중에 comparer 오류가 발생했습니다. 예를 들어 comparer 항목 자체를 비교할 때 0을 반환하지 않을 수 있습니다.

comparernull있고 인터페이스를 구현 IComparable 하지 않는 요소 중 하나 이상 keysArray 입니다.

예제

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

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.

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

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

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

.NET 다음 표에 나열된 미리 정의된 IComparer 구현을 포함합니다.

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

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

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

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

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

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

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

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

호출자 참고

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

추가 정보

적용 대상

Sort(Array, Array)

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

각 키의 구현을 사용하여 IComparable 첫 번째 Array 키에 따라 1차원 Array 개체 쌍(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함)을 정렬합니다.

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

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

-또는-

null 에서만 정렬합니다 keysArray.

예외

keysnull입니다.

keys Array 다차원입니다.

-또는-

items Array 다차원입니다.

items 가 아니 null고 길이가 .의 keysitems길이보다 큽다.

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

예제

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

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 * 로그N을 초과하는 경우 힙소트 알고리즘을 사용합니다.

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

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

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

추가 정보

적용 대상

Sort(Array)

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

각 요소의 구현을 사용하여 IComparable 전체 1차원 Array 의 요소를 정렬합니다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 입니다.

예외

arraynull입니다.

array 가 다차원입니다.

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

예제

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

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 요소는 인터페이스를 IComparable 구현하여 .의 다른 모든 요소 array와 비교할 수 있어야 합니다.

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

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

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

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

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

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

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

추가 정보

적용 대상

Sort(Array, IComparer)

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

지정된 요소를 사용하여 1차원 Array 의 요소를 정렬합니다 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

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

-또는-

각 요소의 구현을 사용하려면 />입니다.

예외

arraynull입니다.

array 가 다차원입니다.

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

정렬 중에 comparer 오류가 발생했습니다. 예를 들어 comparer 항목 자체를 비교할 때 0을 반환하지 않을 수 있습니다.

예제

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

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

설명

이 경우 comparer 각 요소는 인터페이스를 arrayIComparable 구현하여 .의 다른 모든 요소array와 비교할 수 있어야 null합니다.

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

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

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

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

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

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

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

.NET 다음 표에 나열된 미리 정의된 IComparer 구현을 포함합니다.

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

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

호출자 참고

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

추가 정보

적용 대상

Sort<T>(T[])

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

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

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 값입니다.

예외

arraynull입니다.

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

예제

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

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

메모

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

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

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 는 .의 Lengtharray작업입니다.

추가 정보

적용 대상

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

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

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

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> 사용하는 제네릭 인터페이스 구현입니다.

예외

arraynull입니다.

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

정렬 중에 comparer 오류가 발생했습니다. 예를 들어 comparer 항목 자체를 비교할 때 0을 반환하지 않을 수 있습니다.

예제

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

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

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

메모

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

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

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.

설명

null경우 comparer 각 요소는 array 제네릭 인터페이스를 IComparable<T> 구현하여 .의 다른 모든 요소array와 비교할 수 있어야 합니다.

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

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

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

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

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

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

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

호출자 참고

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

추가 정보

적용 대상

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

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

지정한 을 사용하여 요소를 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> 요소를 비교할 때 사용할 수 있습니다.

예외

arraynull입니다.

-또는-

comparisonnull입니다.

정렬 중에 comparison 오류가 발생했습니다. 예를 들어 comparison 항목 자체를 비교할 때 0을 반환하지 않을 수 있습니다.

예제

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

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

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

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 는 .의 Lengtharray작업입니다.

호출자 참고

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

추가 정보

적용 대상

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

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

각 요소의 제네릭 인터페이스 구현을 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

정렬할 범위의 요소 수입니다.

예외

arraynull입니다.

index 가 .의 array하한보다 작습니다.

-또는-

length가 0보다 작습니다.

index 에서 length 유효한 범위를 array지정하지 않습니다.

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

예제

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

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

코드 예제에서는 공룡 이름의 배열을 만들고 표시, 세 초식 동물로 구성 된 다음 세 육식 동물 (tyrannosaurids, 정확 하 게). Sort<T>(T[], Int32, Int32) 제네릭 메서드 오버로드는 배열의 마지막 세 요소를 정렬하는 데 사용되며, 그런 다음 표시됩니다. Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 제네릭 메서드 오버로드는 마지막 세 요소를 역순으로 ReverseCompare 정렬하는 데 사용됩니다. 완전히 혼란스러운 공룡이 다시 표시됩니다.

메모

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

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

설명

지정된 요소 array 범위 내의 각 요소는 제네릭 인터페이스를 IComparable<T>array구현해야 합니다.

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

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

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

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

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

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

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

추가 정보

적용 대상

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

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

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

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> 사용하는 제네릭 인터페이스 구현입니다.

예외

arraynull입니다.

index 가 .의 array하한보다 작습니다.

-또는-

length가 0보다 작습니다.

index 에서 length 유효한 범위를 array지정하지 않습니다.

-또는-

정렬 중에 comparer 오류가 발생했습니다. 예를 들어 comparer 항목 자체를 비교할 때 0을 반환하지 않을 수 있습니다.

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

예제

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

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

코드 예제에서는 공룡 이름의 배열을 만들고 표시, 세 초식 동물로 구성 된 다음 세 육식 동물 (tyrannosaurids, 정확 하 게). Sort<T>(T[], Int32, Int32) 제네릭 메서드 오버로드는 배열의 마지막 세 요소를 정렬하는 데 사용되며, 그런 다음 표시됩니다. Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 제네릭 메서드 오버로드는 마지막 세 요소를 역순으로 ReverseCompare 정렬하는 데 사용됩니다. 완전히 혼란스러운 공룡이 다시 표시됩니다.

메모

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

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

설명

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

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

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

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

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

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

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

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

호출자 참고

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

추가 정보

적용 대상

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

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

지정된 IComparer<T> 제네릭 인터페이스를 사용하여 첫 번째 Array 키에 따라 개체 쌍의 Array 요소 범위를 정렬합니다(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함).

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차원 0부터 Array 시작하는 값입니다.

items
TValue[]

키에 해당하는 항목을 포함하거나 null 정렬 전용keys인 0부터 Array 시작하는 1keys차원입니다.

index
Int32

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

length
Int32

정렬할 범위의 요소 수입니다.

comparer
IComparer<TKey>

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

예외

keysnull입니다.

index 가 .의 keys하한보다 작습니다.

-또는-

length가 0보다 작습니다.

items 가 아니 null고 하한이 .의 keys 하한 items과 일치하지 않습니다.

-또는-

items 가 아니 null고 길이가 .의 keysitems길이보다 큽다.

-또는-

indexlength 유효한 범위를 keysArray지정하지 마세요.

-또는-

items 가 아닌 null경우 . 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<string>(Visual Basic IComparer(Of String)) 제네릭 인터페이스를 구현하는 ReverseCompare 문자열에 대한 대체 비교자를 정의합니다. 비교자는 메서드를 CompareTo(String) 호출하여 비교값의 순서를 반대로 하여 문자열이 낮음에서 높음으로 정렬하는 대신 높음에서 낮은 값으로 정렬되도록 합니다.

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

메모

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

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.

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

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

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

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

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

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

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

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

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

호출자 참고

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

추가 정보

적용 대상

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

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

각 키의 Array 제네릭 인터페이스 구현을 사용하여 IComparable<T> 첫 번째 Array 키에 따라 개체 쌍(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함)을 정렬합니다.

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차원 0부터 Array 시작하는 값입니다.

items
TValue[]

키에 해당하는 항목을 포함하거나 null 정렬 전용keys인 0부터 Array 시작하는 1keys차원입니다.

예외

keysnull입니다.

items 가 아니 null고 하한이 .의 keys 하한 items과 일치하지 않습니다.

-또는-

items 가 아니 null고 길이가 .의 keysitems길이보다 큽다.

하나 이상의 요소가 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<string>(Visual Basic IComparer(Of String)) 제네릭 인터페이스를 구현하는 ReverseCompare 문자열에 대한 대체 비교자를 정의합니다. 비교자는 메서드를 CompareTo(String) 호출하여 비교값의 순서를 반대로 하여 문자열이 낮음에서 높음으로 정렬하는 대신 높음에서 낮은 값으로 정렬되도록 합니다.

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

메모

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

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 는 .의 Lengtharray작업입니다.

추가 정보

적용 대상

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

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

지정된 IComparer<T> 제네릭 인터페이스를 사용하여 첫 번째 Array 키에 따라 개체 쌍Array(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함)을 정렬합니다.

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차원 0부터 Array 시작하는 값입니다.

items
TValue[]

키에 해당하는 항목을 포함하거나 null 정렬 전용keys인 0부터 Array 시작하는 1keys차원입니다.

comparer
IComparer<TKey>

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

예외

keysnull입니다.

items 가 아니 null고 하한이 .의 keys 하한 items과 일치하지 않습니다.

-또는-

items 가 아니 null고 길이가 .의 keysitems길이보다 큽다.

-또는-

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

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

메모

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

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.

이 경우 comparer 각 키는 keysArray 다른 모든 키와 비교할 수 있도록 제네릭 인터페이스를 구현 IComparable<T> 해야 null합니다.

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

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

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

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

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

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

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

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

호출자 참고

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

추가 정보

적용 대상

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

Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs
Source:
Array.cs

각 키의 제네릭 인터페이스 구현을 사용하여 IComparable<T> 첫 번째 Array 키에 따라 개체 쌍의 Array 요소 범위를 정렬합니다(하나는 키를 포함하고 다른 하나는 해당 항목을 포함함).

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차원 0부터 Array 시작하는 값입니다.

items
TValue[]

키에 해당하는 항목을 포함하거나 null 정렬 전용keys인 0부터 Array 시작하는 1keys차원입니다.

index
Int32

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

length
Int32

정렬할 범위의 요소 수입니다.

예외

keysnull입니다.

index 가 .의 keys하한보다 작습니다.

-또는-

length가 0보다 작습니다.

items 가 아니 null고 하한이 .의 keys 하한 items과 일치하지 않습니다.

-또는-

items 가 아니 null고 길이가 .의 keysitems길이보다 큽다.

-또는-

indexlength 유효한 범위를 keysArray지정하지 마세요.

-또는-

items 가 아닌 null경우 . 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[])줍니다.

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

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

메모

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

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 는 다음과 같습니다 length.

추가 정보

적용 대상