Array.Sort Array.Sort Array.Sort Array.Sort Method

定義

1 次元配列の要素を並べ替えます。Sorts the elements in a one-dimensional array.

オーバーロード

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

1 次元 Array の範囲内の要素範囲を、指定した IComparer を使用して並べ替えます。Sorts the elements in a range of elements in a one-dimensional Array using the specified IComparer.

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

2 つの 1 次元 Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) 内の要素範囲を、最初の Array 内のキーに基づき、指定した IComparer を使用して並べ替えます。Sorts a range of elements in a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer.

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

Array の各要素によって実装された IComparable を使用して、1 次元 Array の要素範囲を並べ替えます。Sorts the elements in a range of elements in a one-dimensional Array using the IComparable implementation of each element of the Array.

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

2 つの 1 次元 Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) の要素範囲を、最初の Array 内のキーに基づき、各キーによって実装された IComparable を使用して並べ替えます。Sorts a range of elements in a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

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

1 次元 Array 内の要素を、指定した IComparer を使用して並べ替えます。Sorts the elements in a one-dimensional Array using the specified IComparer.

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

2 つの 1 次元 Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) を、最初の Array 内のキーに基づき、指定した IComparer を使用して並べ替えます。Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer.

Sort(Array, Array) Sort(Array, Array) Sort(Array, Array) Sort(Array, Array)

2 つの 1 次元 Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) を、最初の Array 内のキーに基づき、各キーによって実装された IComparable を使用して並べ替えます。Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

Sort(Array) Sort(Array) Sort(Array)

Array の各要素によって実装された IComparable を使用して、1 次元 Array 全体の要素を並べ替えます。Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.

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

Array の各要素によって実装された IComparable<T> ジェネリック インターフェイスを使用して、Array 全体の要素を並べ替えます。Sorts the elements in an entire Array using the IComparable<T> generic interface implementation of each element of the Array.

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

Array 内の要素を、指定した IComparer<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts the elements in an Array using the specified IComparer<T> generic interface.

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

Array 内の要素を、指定した Comparison<T> を使用して並べ替えます。Sorts the elements in an Array using the specified Comparison<T>.

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

Array の各要素によって実装された IComparable<T> ジェネリック インターフェイスを使用して、Array の要素範囲を並べ替えます。Sorts the elements in a range of elements in an Array using the IComparable<T> generic interface implementation of each element of the Array.

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

指定した Array ジェネリック インターフェイスを使用して、IComparer<T> 内の要素範囲を並べ替えます。Sorts the elements in a range of elements in an Array using the specified IComparer<T> generic interface.

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

2 つの Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) を、最初の Array 内のキーに基づき、各キーによって実装された IComparable<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable<T> generic interface implementation of each key.

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

2 つの Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) を、最初の Array 内のキーに基づき、指定した IComparer<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer<T> generic interface.

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

2 つの Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) の要素範囲を、最初の Array 内のキーに基づき、各キーによって実装された IComparable<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts a range of elements in a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable<T> generic interface implementation of each key.

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

2 つの Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) 内の要素範囲を、最初の Array 内のキーに基づき、指定した IComparer<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts a range of elements in a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer<T> generic interface.

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

1 次元 Array の範囲内の要素範囲を、指定した IComparer を使用して並べ替えます。Sorts the elements in a range of elements in a one-dimensional Array using the specified 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);
static member Sort : Array * int * int * System.Collections.IComparer -> unit

パラメーター

array
Array Array Array Array

並べ替え対象となる 1 次元 ArrayThe one-dimensional Array to sort.

index
Int32 Int32 Int32 Int32

並べ替え対象の範囲の開始位置を示すインデックス。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

並べ替え対象の範囲内にある要素の数。The number of elements in the range to sort.

comparer
IComparer IComparer IComparer IComparer

要素を比較する場合に使用する IComparer の実装。The IComparer implementation to use when comparing elements.

または-or- null 各要素の IComparable 実装を使用する 。to use the IComparable implementation of each element.

例外

array が多次元です。is multidimensional.

index は、array の下限を下回っています。is less than the lower bound of array.

または-or- length が 0 未満です。is less than zero.

index および length では array の有効な範囲は指定されません。and length do not specify a valid range in array.

または-or- comparer の実装により、並べ替え中にエラーが発生しました。The implementation of comparer caused an error during the sort. たとえば、comparer は、項目をそれ自体と比較したときに 0 を返さなかった可能性があります。For example, comparer might not return 0 when comparing an item with itself.

comparer null で、array 内の 1 つまたは複数の要素によって IComparable インターフェイスが実装されていません。is null, and one or more elements in array do not implement the IComparable interface.

次のコード例の値を並べ替える方法を示しています、Array既定の比較子と並べ替え順序を反転するカスタム比較子を使用します。The following code example shows how to sort the values in an Array using the default comparer and a custom comparer that reverses the sort order. 結果は、現在によって異なる場合がありますので注意CultureInfoします。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

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

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

   Console::WriteLine();
}

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

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

public class Example 
{
   public static void Main()  
   {
      // Create and initialize a new array. 
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps", 
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();
 
      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);
 
      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

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

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

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

注釈

場合comparernull、内の要素の指定した範囲内の各要素array実装する必要があります、IComparableの他のすべての要素との比較ができるようにするインターフェイスarrayします。If comparer is null, each element within the specified range of elements in array must implement the IComparable interface to be capable of comparisons with every other element in array.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

.NET Framework が含まれています定義済みIComparer実装は、次の表に一覧表示します。The .NET Framework includes predefined IComparer implementations listed in the following table.

実装Implementation 説明Description
System.Collections.CaseInsensitiveComparer 任意の 2 つのオブジェクトを比較しますが、大文字と小文字の文字列を実行します。Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default 現在のカルチャの並べ替え規則を使用して、2 つのオブジェクトを比較します。Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant インバリアント カルチャの並べ替え規則を使用して、2 つのオブジェクトを比較します。Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default 型の 2 つのオブジェクトを比較T型の既定の並べ替え順序を使用しています。Compares two objects of type T by using the type's default sort order.

独自のインスタンスを提供することで、カスタム比較をサポートすることもIComparerを実装、comparerパラメーター。You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. 定義することでこの例では、ReverseComparerクラスの既定の並べ替え順序を反転する型のインスタンスと大文字の文字列比較を実行します。The example does this by defining a ReverseComparer class that reverses the default sort order for instances of a type and performs case-insensitive string comparison.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nlengthします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

注意 (呼び出し元)

.NET Framework 4 と以前のバージョンは、クイック ソート アルゴリズムのみを使用します。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. クイック ソートは、状況によっては、並べ替え操作がスローされます、無効な比較演算子を識別、 IndexOutOfRangeException 、例外をスローします、ArgumentException呼び出し元の例外。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 以降では、 .NET Framework 4.5.NET Framework 4.5、ことがスローした並べ替え操作がいたことができますArgumentException挿入の並べ替えと heapsort アルゴリズムでは、無効な比較子が検出されないため、例外をスローできません。Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. ほとんどの場合、これよりも少ない 16 個の要素を配列に適用されます。For the most part, this applies to arrays with fewer than 16 elements.

こちらもご覧ください

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

2 つの 1 次元 Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) 内の要素範囲を、最初の Array 内のキーに基づき、指定した IComparer を使用して並べ替えます。Sorts a range of elements in a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer.

public:
 static void Sort(Array ^ keys, Array ^ items, int index, int length, System::Collections::IComparer ^ comparer);
public static void Sort (Array keys, Array items, int index, int length, System.Collections.IComparer comparer);
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 Array Array Array

並べ替え対象となるキーを格納する 1 次元 ArrayThe one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

keysArray 内の各キーに対応する項目を格納する 1 次元 ArrayThe one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

または-or- null keysArray のみを並べ替える場合は 。to sort only the keysArray.

index
Int32 Int32 Int32 Int32

並べ替え対象の範囲の開始位置を示すインデックス。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

並べ替え対象の範囲内にある要素の数。The number of elements in the range to sort.

comparer
IComparer IComparer IComparer IComparer

要素を比較する場合に使用する IComparer の実装。The IComparer implementation to use when comparing elements.

または-or- null 各要素の IComparable 実装を使用する 。to use the IComparable implementation of each element.

例外

keysArray が多次元です。The keysArray is multidimensional.

または-or- itemsArray が多次元です。The itemsArray is multidimensional.

index keys の下限を下回っています。is less than the lower bound of keys.

または-or- length が 0 未満です。is less than zero.

items null ではなく、keys の下限が items の下限と一致していません。is not null, and the lower bound of keys does not match the lower bound of items.

または-or- items null ではなく、keys の長さが items の長さを超えています。is not null, and the length of keys is greater than the length of items.

または-or- index および length によって keysArray 内の有効な範囲が指定されていません。and length do not specify a valid range in the keysArray.

または-or- items null ではなく、index および length によって itemsArray 内の有効な範囲が指定されていません。is not null, and index and length do not specify a valid range in the itemsArray.

または-or- comparer の実装により、並べ替え中にエラーが発生しました。The implementation of comparer caused an error during the sort. たとえば、comparer は、項目をそれ自体と比較したときに 0 を返さなかった可能性があります。For example, comparer might not return 0 when comparing an item with itself.

comparer null であり、keysArray 内の 1 つまたは複数の要素によって IComparable インターフェイスが実装されていません。is null, and one or more elements in the keysArray do not implement the IComparable interface.

次のコード例では、キーと値を格納する 2 番目の配列の 2 つの関連付けられている配列を並べ替える方法を示します。The following code example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. 並べ替えが完了したら、既定の比較子と並べ替え順序を反転するカスタム比較子を使用します。Sorts are done using the default comparer and a custom comparer that reverses the sort order. 結果は、現在によって異なる場合がありますので注意CultureInfoします。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

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

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

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

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

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

   }

   public static void Main()  {
 
      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();
 
      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );
 
      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

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

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

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

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


/* 
This code produces the following output.

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

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

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

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

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

*/

Imports System
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 'myReverserClass


   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 'Main


   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 'PrintKeysAndValues

End Class 'SamplesArray


'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します。Each key in the keysArray has a corresponding item in the itemsArray. 並べ替え、対応する項目の中に、キーが移動したときに、itemsArray同様の位置を変更します。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. そのため、itemsArrayが内の対応するキーの並べ替えに従って並び替え、keysArrayします。Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

場合comparernull、内の要素の指定された範囲内の各キー、keysArray実装する必要があります、IComparable他のすべてのキーの比較ができるようにするインターフェイス。If comparer is null, each key within the specified range of elements in the keysArray must implement the IComparable interface to be capable of comparisons with every other key.

キーよりも項目がありますが、対応するキーのない項目が並べ替えられていない場合は並べ替えることができます。You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. 項目よりも多くのキーがある場合に並べ替えることはできません。スローされること、ArgumentExceptionします。You cannot sort if there are more keys than items; doing this throws an ArgumentException.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

.NET Framework が含まれています定義済みIComparer実装は、次の表に一覧表示します。The .NET Framework includes predefined IComparer implementations listed in the following table.

実装Implementation 説明Description
System.Collections.CaseInsensitiveComparer 任意の 2 つのオブジェクトを比較しますが、大文字と小文字の文字列を実行します。Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default 現在のカルチャの並べ替え規則を使用して、2 つのオブジェクトを比較します。Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant インバリアント カルチャの並べ替え規則を使用して、2 つのオブジェクトを比較します。Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default 型の 2 つのオブジェクトを比較T型の既定の並べ替え順序を使用しています。Compares two objects of type T by using the type's default sort order.

独自のインスタンスを提供することで、カスタム比較をサポートすることもIComparerを実装、comparerパラメーター。You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. この例ではこのカスタムを定義することでIComparer既定の並べ替え順序を反転し、大文字の文字列を比較する実装。The example does this by defining a custom IComparer implementation that reverses the default sort order and performs case-insensitive string comparison.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nlengthします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

注意 (呼び出し元)

.NET Framework 4 と以前のバージョンは、クイック ソート アルゴリズムのみを使用します。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. クイック ソートは、状況によっては、並べ替え操作がスローされます、無効な比較演算子を識別、 IndexOutOfRangeException 、例外をスローします、ArgumentException呼び出し元の例外。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 以降では、 .NET Framework 4.5.NET Framework 4.5、ことがスローした並べ替え操作がいたことができますArgumentException挿入の並べ替えと heapsort アルゴリズムでは、無効な比較子が検出されないため、例外をスローできません。Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. ほとんどの場合、これよりも少ない 16 個の要素を配列に適用されます。For the most part, this applies to arrays with fewer than 16 elements.

こちらもご覧ください

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

Array の各要素によって実装された IComparable を使用して、1 次元 Array の要素範囲を並べ替えます。Sorts the elements in a range of elements in a one-dimensional Array using the IComparable implementation of each element of the 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

パラメーター

array
Array Array Array Array

並べ替え対象となる 1 次元 ArrayThe one-dimensional Array to sort.

index
Int32 Int32 Int32 Int32

並べ替え対象の範囲の開始位置を示すインデックス。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

並べ替え対象の範囲内にある要素の数。The number of elements in the range to sort.

例外

array が多次元です。is multidimensional.

index は、array の下限を下回っています。is less than the lower bound of array.

または-or- length が 0 未満です。is less than zero.

index および length では array の有効な範囲は指定されません。and length do not specify a valid range in array.

array の 1 つ以上の要素が、IComparable インターフェイスを実装していません。One or more elements in array do not implement the IComparable interface.

次のコード例の値を並べ替える方法を示しています、Array既定の比較子と並べ替え順序を反転するカスタム比較子を使用します。The following code example shows how to sort the values in an Array using the default comparer and a custom comparer that reverses the sort order. 結果は、現在によって異なる場合がありますので注意CultureInfoします。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

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

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

   Console::WriteLine();
}

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

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

public class Example 
{
   public static void Main()  
   {
      // Create and initialize a new array. 
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps", 
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();
 
      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);
 
      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

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

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

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }
 
   public static void DisplayValues(String[] arr)  
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//    
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN    
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します。Each element within the specified range of elements in array must implement the IComparable interface to be capable of comparisons with every other element in array.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nlengthします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

こちらもご覧ください

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

2 つの 1 次元 Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) の要素範囲を、最初の Array 内のキーに基づき、各キーによって実装された IComparable を使用して並べ替えます。Sorts a range of elements in a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

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 Array Array Array

並べ替え対象となるキーを格納する 1 次元 ArrayThe one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

keysArray 内の各キーに対応する項目を格納する 1 次元 ArrayThe one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

または-or- null keysArray のみを並べ替える場合は 。to sort only the keysArray.

index
Int32 Int32 Int32 Int32

並べ替え対象の範囲の開始位置を示すインデックス。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

並べ替え対象の範囲内にある要素の数。The number of elements in the range to sort.

例外

keysArray が多次元です。The keysArray is multidimensional.

または-or- itemsArray が多次元です。The itemsArray is multidimensional.

index keys の下限を下回っています。is less than the lower bound of keys.

または-or- length が 0 未満です。is less than zero.

items null ではなく、keys の長さが items の長さを超えています。is not null, and the length of keys is greater than the length of items.

または-or- index および length によって keysArray 内の有効な範囲が指定されていません。and length do not specify a valid range in the keysArray.

または-or- items null ではなく、index および length によって itemsArray 内の有効な範囲が指定されていません。is not null, and index and length do not specify a valid range in the itemsArray.

keysArray 内の 1 つまたは複数の要素に IComparable インターフェイスが実装されていません。One or more elements in the keysArray do not implement the IComparable interface.

次のコード例では、キーと値を格納する 2 番目の配列の 2 つの関連付けられている配列を並べ替える方法を示します。The following code example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. 並べ替えが完了したら、既定の比較子と並べ替え順序を反転するカスタム比較子を使用します。Sorts are done using the default comparer and a custom comparer that reverses the sort order. 結果は、現在によって異なる場合がありますので注意CultureInfoします。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

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

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

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

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

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

   }

   public static void Main()  {
 
      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();
 
      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );
 
      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

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

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

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

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


/* 
This code produces the following output.

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

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

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

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

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

*/

Imports System
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 'myReverserClass


   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 'Main


   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 'PrintKeysAndValues

End Class 'SamplesArray


'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します。Each key in the keysArray has a corresponding item in the itemsArray. 並べ替え、対応する項目の中に、キーが移動したときに、itemsArray同様の位置を変更します。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. そのため、itemsArrayが内の対応するキーの並べ替えに従って並び替え、keysArrayします。Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

指定した範囲内の要素の各キー、keysArray実装する必要があります、IComparable他のすべてのキーの比較ができるようにするインターフェイス。Each key within the specified range of elements in the keysArray must implement the IComparable interface to be capable of comparisons with every other key.

キーよりも項目がありますが、対応するキーのない項目が並べ替えられていない場合は並べ替えることができます。You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. 項目よりも多くのキーがある場合に並べ替えることはできません。スローされること、ArgumentExceptionします。You cannot sort if there are more keys than items; doing this throws an ArgumentException.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nlengthします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

こちらもご覧ください

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

1 次元 Array 内の要素を、指定した IComparer を使用して並べ替えます。Sorts the elements in a one-dimensional Array using the specified IComparer.

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

パラメーター

array
Array Array Array Array

並べ替え対象となる 1 次元配列。The one-dimensional array to sort.

comparer
IComparer IComparer IComparer IComparer

要素を比較する場合に使用する実装。The implementation to use when comparing elements.

または-or- null 各要素の IComparable 実装を使用する 。to use the IComparable implementation of each element.

例外

array が多次元です。is multidimensional.

comparer null で、array 内の 1 つまたは複数の要素によって IComparable インターフェイスが実装されていません。is null, and one or more elements in array do not implement the IComparable interface.

comparer の実装により、並べ替え中にエラーが発生しました。The implementation of comparer caused an error during the sort. たとえば、comparer は、項目をそれ自体と比較したときに 0 を返さなかった可能性があります。For example, comparer might not return 0 when comparing an item with itself.

次の例には、既定の比較子を使用して、文字列配列に値が並べ替えられます。The following example sorts the values in a string array by using the default comparer. カスタムも定義されています。IComparerという名前の実装ReverseComparer大文字の文字列比較の実行中に、オブジェクトの既定の並べ替え順序を反転します。It also defines a custom IComparer implementation named ReverseComparer that reverses an object's default sort order while performing a case-insensitive string comparison. 出力は、現在のカルチャによって異なる場合がありますに注意してください。Note that the output might vary depending on the current culture.

using namespace System;
using namespace System::Collections;

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

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

   Console::WriteLine();
}

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

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

public class Example 
{
   public static void Main()  
   {
      // Create and initialize a new array. 
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps", 
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();
 
      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);
 
      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

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

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

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

注釈

場合comparernullの各要素array実装する必要があります、IComparableの他のすべての要素との比較ができるようにするインターフェイスarrayします。If comparer is null, each element of array must implement the IComparable interface to be capable of comparisons with every other element in array.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nは、Lengtharrayします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

.NET Framework が含まれています定義済みIComparer実装は、次の表に一覧表示します。The .NET Framework includes predefined IComparer implementations listed in the following table.

実装Implementation 説明Description
System.Collections.CaseInsensitiveComparer 任意の 2 つのオブジェクトを比較しますが、大文字と小文字の文字列を実行します。Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default 現在のカルチャの並べ替え規則を使用して、2 つのオブジェクトを比較します。Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant インバリアント カルチャの並べ替え規則を使用して、2 つのオブジェクトを比較します。Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default 型の 2 つのオブジェクトを比較T型の既定の並べ替え順序を使用しています。Compares two objects of type T by using the type's default sort order.

独自のインスタンスを提供することで、カスタム比較をサポートすることもIComparerを実装、comparerパラメーター。You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. 定義することでこの例では、ReverseComparerクラスの既定の並べ替え順序を反転する型のインスタンスと大文字の文字列比較を実行します。The example does this by defining a ReverseComparer class that reverses the default sort order for instances of a type and performs case-insensitive string comparison.

注意 (呼び出し元)

.NET Framework 4 と以前のバージョンは、クイック ソート アルゴリズムのみを使用します。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. クイック ソートは、状況によっては、並べ替え操作がスローされます、無効な比較演算子を識別、 IndexOutOfRangeException 、例外をスローします、ArgumentException呼び出し元の例外。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 以降では、 .NET Framework 4.5.NET Framework 4.5、ことがスローした並べ替え操作がいたことができますArgumentException挿入の並べ替えと heapsort アルゴリズムでは、無効な比較子が検出されないため、例外をスローできません。Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. ほとんどの場合、これよりも少ない 16 個の要素を配列に適用されます。For the most part, this applies to arrays with fewer than 16 elements.

こちらもご覧ください

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

2 つの 1 次元 Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) を、最初の Array 内のキーに基づき、指定した IComparer を使用して並べ替えます。Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer.

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

パラメーター

keys
Array Array Array Array

並べ替え対象となるキーを格納する 1 次元 ArrayThe one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

keysArray 内の各キーに対応する項目を格納する 1 次元 ArrayThe one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

または-or- null keysArray のみを並べ替える場合は 。to sort only the keysArray.

comparer
IComparer IComparer IComparer IComparer

要素を比較する場合に使用する IComparer の実装。The IComparer implementation to use when comparing elements.

または-or- null 各要素の IComparable 実装を使用する 。to use the IComparable implementation of each element.

例外

keysArray が多次元です。The keysArray is multidimensional.

または-or- itemsArray が多次元です。The itemsArray is multidimensional.

items null ではなく、keys の長さが items の長さを超えています。is not null, and the length of keys is greater than the length of items.

または-or- comparer の実装により、並べ替え中にエラーが発生しました。The implementation of comparer caused an error during the sort. たとえば、comparer は、項目をそれ自体と比較したときに 0 を返さなかった可能性があります。For example, comparer might not return 0 when comparing an item with itself.

comparer null であり、keysArray 内の 1 つまたは複数の要素によって IComparable インターフェイスが実装されていません。is null, and one or more elements in the keysArray do not implement the IComparable interface.

次の例では、キーと値を格納する 2 番目の配列の 2 つの関連付けられている配列を並べ替える方法を示します。The following example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. 並べ替えが完了したら、既定の比較子と並べ替え順序を反転するカスタム比較子を使用します。Sorts are done using the default comparer and a custom comparer that reverses the sort order. 結果は、現在によって異なる場合がありますので注意CultureInfoします。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

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

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

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

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

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

   }

   public static void Main()  {
 
      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();
 
      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );
 
      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

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

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

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

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


/* 
This code produces the following output.

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

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

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

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

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

*/

Imports System
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 'myReverserClass


   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 'Main


   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 'PrintKeysAndValues

End Class 'SamplesArray


'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します。Each key in the keysArray has a corresponding item in the itemsArray. 並べ替え、対応する項目の中に、キーが移動したときに、itemsArray同様の位置を変更します。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. そのため、itemsArrayが内の対応するキーの並べ替えに従って並び替え、keysArrayします。Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

場合comparernull、それぞれのキー、keysArray実装する必要があります、IComparable他のすべてのキーの比較ができるようにするインターフェイス。If comparer is null, each key in the keysArray must implement the IComparable interface to be capable of comparisons with every other key.

キーよりも項目がありますが、対応するキーのない項目が並べ替えられていない場合は並べ替えることができます。You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. 項目よりも多くのキーがある場合に並べ替えることはできません。スローされること、ArgumentExceptionします。You cannot sort if there are more keys than items; doing this throws an ArgumentException.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

.NET Framework が含まれています定義済みIComparer実装は、次の表に一覧表示します。The .NET Framework includes predefined IComparer implementations listed in the following table.

実装Implementation 説明Description
System.Collections.CaseInsensitiveComparer 任意の 2 つのオブジェクトを比較しますが、大文字と小文字の文字列を実行します。Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default 現在のカルチャの並べ替え規則を使用して、2 つのオブジェクトを比較します。Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant インバリアント カルチャの並べ替え規則を使用して、2 つのオブジェクトを比較します。Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default 型の 2 つのオブジェクトを比較T型の既定の並べ替え順序を使用しています。Compares two objects of type T by using the type's default sort order.

独自のインスタンスを提供することで、カスタム比較をサポートすることもIComparerを実装、comparerパラメーター。You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. 定義することでこの例では、IComparer既定の並べ替え順序を反転し、大文字の文字列を比較する実装。The example does this by defining an IComparer implementation that reverses the default sort order and performs case-insensitive string comparison.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nは、Lengthkeysします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of keys.

注意 (呼び出し元)

.NET Framework 4 と以前のバージョンは、クイック ソート アルゴリズムのみを使用します。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. クイック ソートは、状況によっては、並べ替え操作がスローされます、無効な比較演算子を識別、 IndexOutOfRangeException 、例外をスローします、ArgumentException呼び出し元の例外。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 以降では、 .NET Framework 4.5.NET Framework 4.5、ことがスローした並べ替え操作がいたことができますArgumentException挿入の並べ替えと heapsort アルゴリズムでは、無効な比較子が検出されないため、例外をスローできません。Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. ほとんどの場合、これよりも少ない 16 個の要素を配列に適用されます。For the most part, this applies to arrays with fewer than 16 elements.

こちらもご覧ください

Sort(Array, Array) Sort(Array, Array) Sort(Array, Array) Sort(Array, Array)

2 つの 1 次元 Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) を、最初の Array 内のキーに基づき、各キーによって実装された IComparable を使用して並べ替えます。Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

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 Array Array Array

並べ替え対象となるキーを格納する 1 次元 ArrayThe one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

keysArray 内の各キーに対応する項目を格納する 1 次元 ArrayThe one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

または-or- null keysArray のみを並べ替える場合は 。to sort only the keysArray.

例外

keysArray が多次元です。The keysArray is multidimensional.

または-or- itemsArray が多次元です。The itemsArray is multidimensional.

items null ではなく、keys の長さが items の長さを超えています。is not null, and the length of keys is greater than the length of items.

keysArray 内の 1 つまたは複数の要素に IComparable インターフェイスが実装されていません。One or more elements in the keysArray do not implement the IComparable interface.

次の例では、キーと値を格納する 2 番目の配列の 2 つの関連付けられている配列を並べ替える方法を示します。The following example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. 並べ替えが完了したら、既定の比較子と並べ替え順序を反転するカスタム比較子を使用します。Sorts are done using the default comparer and a custom comparer that reverses the sort order. 結果は、現在によって異なる場合がありますので注意CultureInfoします。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

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

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

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

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

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

   }

   public static void Main()  {
 
      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();
 
      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );
 
      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

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

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

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

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


/* 
This code produces the following output.

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

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

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

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

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

*/

Imports System
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 'myReverserClass


   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 'Main


   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 'PrintKeysAndValues

End Class 'SamplesArray


'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します。Each key in the keysArray has a corresponding item in the itemsArray. 並べ替え、対応する項目の中に、キーが移動したときに、itemsArray同様の位置を変更します。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. そのため、itemsArrayが内の対応するキーの並べ替えに従って並び替え、keysArrayします。Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

各キーに、keysArray実装する必要があります、IComparable他のすべてのキーの比較ができるようにするインターフェイス。Each key in the keysArray must implement the IComparable interface to be capable of comparisons with every other key.

キーよりも項目がありますが、対応するキーのない項目が並べ替えられていない場合は並べ替えることができます。You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. 項目よりも多くのキーがある場合に並べ替えることはできません。スローされること、ArgumentExceptionします。You cannot sort if there are more keys than items; doing this throws an ArgumentException.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nは、Lengthkeysします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of keys.

こちらもご覧ください

Sort(Array) Sort(Array) Sort(Array)

Array の各要素によって実装された IComparable を使用して、1 次元 Array 全体の要素を並べ替えます。Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.

public:
 static void Sort(Array ^ array);
public static void Sort (Array array);
static member Sort : Array -> unit

パラメーター

array
Array Array Array Array

並べ替え対象となる 1 次元 ArrayThe one-dimensional Array to sort.

例外

array が多次元です。is multidimensional.

array の 1 つ以上の要素が、IComparable インターフェイスを実装していません。One or more elements in array do not implement the IComparable interface.

次のコード例の値を並べ替える方法を示しています、Array既定の比較子と並べ替え順序を反転するカスタム比較子を使用します。The following code example shows how to sort the values in an Array using the default comparer and a custom comparer that reverses the sort order. 結果は、現在によって異なる場合がありますので注意CultureInfoします。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

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

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

   Console::WriteLine();
}

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

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

public class Example 
{
   public static void Main()  
   {
      // Create and initialize a new array. 
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps", 
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();
 
      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);
 
      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

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

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

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }
 
   public static void DisplayValues(String[] arr)  
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//    
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN    
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します。Each element of array must implement the IComparable interface to be capable of comparisons with every other element in array.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nは、Lengtharrayします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

こちらもご覧ください

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

Array の各要素によって実装された IComparable<T> ジェネリック インターフェイスを使用して、Array 全体の要素を並べ替えます。Sorts the elements in an entire Array using the IComparable<T> generic interface implementation of each element of the Array.

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

型パラメーター

T

配列要素の型。The type of the elements of the array.

パラメーター

array
T[]

並べ替え対象となる、インデックス番号が 0 から始まる 1 次元 ArrayThe one-dimensional, zero-based Array to sort.

例外

array の 1 つ以上の要素が、IComparable<T> ジェネリック インターフェイスを実装していません。One or more elements in array do not implement the IComparable<T> generic interface.

次のコード例に示します、Sort<T>(T[])ジェネリック メソッドのオーバー ロードとBinarySearch<T>(T[], T)ジェネリック メソッドのオーバー ロードします。The following code example demonstrates the Sort<T>(T[]) generic method overload and the BinarySearch<T>(T[], T) generic method overload. 文字列の配列は、任意の順序に作成されます。An array of strings is created, in no particular order.

配列が表示され、並べ替え、もう一度表示されます。The array is displayed, sorted, and displayed again.

注意

呼び出し、SortBinarySearchVisual Basic、c#、および C++ は、最初の引数の型とジェネリック型パラメーターの型を推論するため、ジェネリック メソッドの呼び出しを非ジェネリックの対応する間に違い探さないです。The calls to the Sort and BinarySearch generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first argument. 使用する場合、 Ildasm.exe (IL Disassembler)を Microsoft intermediate language (MSIL) を確認するには、ジェネリック メソッドが呼び出されることを確認できます。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

BinarySearch<T>(T[], T)ジェネリック メソッドのオーバー ロードが 2 つの文字列を検索するために使用しではない配列および 1 つを 1 つです。The BinarySearch<T>(T[], T) generic method overload is then used to search for two strings, one that is not in the array and one that is. 配列との戻り値、BinarySearchメソッドに渡される、ShowWhereジェネリック メソッドは、それ以外の場合、要素検索文字列が間に、配列を使用した場合、文字列が見つかった場合は、インデックス値を表示します。The array and the return value of the BinarySearch method are passed to the ShowWhere generic method, which displays the index value if the string is found, and otherwise the elements the search string would fall between if it were in the array. インデックスが負の値、文字列は、n がない場合、配列のため、ShowWhereメソッドは、ビットごとの補数 (、~ c# および Visual C は、演算子XorVisual Basic で-1) 検索からよりも大きい一覧の最初の要素のインデックスを取得するにはng です。The index is negative if the string is not n the array, so the ShowWhere method takes the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) to obtain the index of the first element in the list that is larger than the search string.

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

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

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

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

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

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

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

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

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

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

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

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

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

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

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

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

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

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

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

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

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

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

BinarySearch for 'Tyrannosaurus':
Found at index 5.
 */
Imports System
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します。Each element of array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nは、Lengtharrayします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

こちらもご覧ください

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

Array 内の要素を、指定した IComparer<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts the elements in an Array using the specified IComparer<T> generic interface.

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

配列要素の型。The type of the elements of the array.

パラメーター

array
T[]

並べ替える 1 次元の Array。インデックス番号が 0 から始まる必要があります。The one-dimensional, zero-base Array to sort

comparer
IComparer<T> IComparer<T> IComparer<T> IComparer<T>

要素を比較する際に使用する IComparer<T> ジェネリック インターフェイスの実装。各要素が実装する IComparable<T> ジェネリック インターフェイスを使用する場合は nullThe IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

例外

comparer null であり、array 内の 1 つまたは複数の要素によって IComparable<T> ジェネリック インターフェイスが実装されていません。is null, and one or more elements in array do not implement the IComparable<T> generic interface.

comparer の実装により、並べ替え中にエラーが発生しました。The implementation of comparer caused an error during the sort. たとえば、comparer は、項目をそれ自体と比較したときに 0 を返さなかった可能性があります。For example, comparer might not return 0 when comparing an item with itself.

次のコード例に示します、Sort<T>(T[], IComparer<T>)ジェネリック メソッドのオーバー ロードとBinarySearch<T>(T[], T, IComparer<T>)ジェネリック メソッドのオーバー ロードします。The following code example demonstrates the Sort<T>(T[], IComparer<T>) generic method overload and the BinarySearch<T>(T[], T, IComparer<T>) generic method overload.

コード例では、という名前の文字列の代替の比較子を定義します。 ReverseCompare、実装、 IComparer<string> (IComparer(Of String) Visual basic でIComparer<String^>Visual c で) ジェネリック インターフェイス。The code example defines an alternative comparer for strings, named ReverseCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. 比較演算子の呼び出し、CompareTo(String)メソッドは、文字列は、低-高のではなく高から低を並べ替えられるように、比較対照値の順序を反転します。The comparer calls the CompareTo(String) method, reversing the order of the comparands so that the strings sort high-to-low instead of low-to-high.

配列が表示され、並べ替え、もう一度表示されます。The array is displayed, sorted, and displayed again. 使用するには、配列を並べ替える必要があります、BinarySearchメソッド。Arrays must be sorted in order to use the BinarySearch method.

注意

呼び出し、Sort<T>(T[], IComparer<T>)BinarySearch<T>(T[], T, IComparer<T>)Visual Basic、c#、および C++ は、最初の引数の型とジェネリック型パラメーターの型を推論するため、ジェネリック メソッドの呼び出しを非ジェネリックの対応する間に違い探さないです。The calls to the Sort<T>(T[], IComparer<T>) and BinarySearch<T>(T[], T, IComparer<T>) generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first argument. 使用する場合、 Ildasm.exe (IL Disassembler)を Microsoft intermediate language (MSIL) を確認するには、ジェネリック メソッドが呼び出されることを確認できます。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

BinarySearch<T>(T[], T, IComparer<T>)ジェネリック メソッドのオーバー ロードが 2 つの文字列を検索するために使用しではない配列および 1 つを 1 つです。The BinarySearch<T>(T[], T, IComparer<T>) generic method overload is then used to search for two strings, one that is not in the array and one that is. 配列との戻り値、BinarySearch<T>(T[], T, IComparer<T>)メソッドに渡される、ShowWhereジェネリック メソッドは、それ以外の場合、要素検索文字列が間に、配列を使用した場合、文字列が見つかった場合は、インデックス値を表示します。The array and the return value of the BinarySearch<T>(T[], T, IComparer<T>) method are passed to the ShowWhere generic method, which displays the index value if the string is found, and otherwise the elements the search string would fall between if it were in the array. インデックスが負の値、文字列は、n がない場合、配列のため、ShowWhereメソッドは、ビットごとの補数 (、~ c# および Visual C は、演算子XorVisual Basic で-1) 検索からよりも大きい一覧の最初の要素のインデックスを取得するにはng です。The index is negative if the string is not n the array, so the ShowWhere method takes the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) to obtain the index of the first element in the list that is larger than the search string.

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

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus

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

BinarySearch for 'Tyrannosaurus':
Found at index 0.
 */
Imports System
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.

注釈

場合comparernullの各要素array実装する必要があります、IComparable<T>ジェネリック インターフェイスの他のすべての要素との比較ができるようにするarrayします。If comparer is null, each element of array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nは、Lengtharrayします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

注意 (呼び出し元)

.NET Framework 4 と以前のバージョンは、クイック ソート アルゴリズムのみを使用します。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. クイック ソートは、状況によっては、並べ替え操作がスローされます、無効な比較演算子を識別、 IndexOutOfRangeException 、例外をスローします、ArgumentException呼び出し元の例外。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 以降では、 .NET Framework 4.5.NET Framework 4.5、ことがスローした並べ替え操作がいたことができますArgumentException挿入の並べ替えと heapsort アルゴリズムでは、無効な比較子が検出されないため、例外をスローできません。Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. ほとんどの場合、これよりも少ない 16 個の要素を配列に適用されます。For the most part, this applies to arrays with fewer than 16 elements.

こちらもご覧ください

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

Array 内の要素を、指定した Comparison<T> を使用して並べ替えます。Sorts the elements in an Array using the specified 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

配列要素の型。The type of the elements of the array.

パラメーター

array
T[]

並べ替える 1 次元の Array。インデックス番号が 0 から始まる必要があります。The one-dimensional, zero-based Array to sort

comparison
Comparison<T> Comparison<T> Comparison<T> Comparison<T>

要素を比較する場合に使用する Comparison<T>The Comparison<T> to use when comparing elements.

例外

array null です。is null.

または-or- comparison null です。is null.

comparison の実装により、並べ替え中にエラーが発生しました。The implementation of comparison caused an error during the sort. たとえば、comparison は、項目をそれ自体と比較したときに 0 を返さなかった可能性があります。For example, comparison might not return 0 when comparing an item with itself.

次のコード例に示します、Sort(Comparison<T>)メソッドのオーバー ロードします。The following code example demonstrates the Sort(Comparison<T>) method overload.

コード例は、という名前の文字列の代替の比較メソッドを定義CompareDinosByLengthします。The code example defines an alternative comparison method for strings, named CompareDinosByLength. このメソッドは、次のように機能します。最初にの比較対照値がテストされますnull、null 参照が null でない未満として扱われます。This method works as follows: First, the comparands are tested fornull, and a null reference is treated as less than a non-null. 次に、文字列の長さを比較してより長い文字列が大きいと見なされます。Second, the string lengths are compared, and the longer string is deemed to be greater. 3 番目に、長さが等しい場合は、通常の文字列比較が使用されます。Third, if the lengths are equal, ordinary string comparison is used.

文字列の配列が作成され、任意の順序で、4 つの文字列に設定されます。A array of strings is created and populated with four strings, in no particular order. 一覧には、空の文字列と null 参照も含まれています。The list also includes an empty string and a null reference. 一覧を表示すると、並べ替えを使用して、Comparison<T>を表すジェネリック デリゲート、CompareDinosByLengthメソッドを再び表示されます。The list is displayed, sorted using a Comparison<T> generic delegate representing the CompareDinosByLength method, and displayed again.

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

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

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

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

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

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

}

/* This code example produces the following output:

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

Sort with generic Comparison<String^> delegate:

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

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

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

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

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

    }

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

/* This code example produces the following output:

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

Sort with generic Comparison<string> delegate:

(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
 */
Imports System
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"

注釈

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nは、Lengtharrayします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

注意 (呼び出し元)

.NET Framework 4 と以前のバージョンは、クイック ソート アルゴリズムのみを使用します。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. クイック ソートは、状況によっては、並べ替え操作がスローされます、無効な比較演算子を識別、 IndexOutOfRangeException 、例外をスローします、ArgumentException呼び出し元の例外。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 以降では、 .NET Framework 4.5.NET Framework 4.5、ことがスローした並べ替え操作がいたことができますArgumentException挿入の並べ替えと heapsort アルゴリズムでは、無効な比較子が検出されないため、例外をスローできません。Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. ほとんどの場合、これよりも少ない 16 個の要素を配列に適用されます。For the most part, this applies to arrays with fewer than 16 elements.

こちらもご覧ください

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

Array の各要素によって実装された IComparable<T> ジェネリック インターフェイスを使用して、Array の要素範囲を並べ替えます。Sorts the elements in a range of elements in an Array using the IComparable<T> generic interface implementation of each element of the 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

配列要素の型。The type of the elements of the array.

パラメーター

array
T[]

並べ替える 1 次元の Array。インデックス番号が 0 から始まる必要があります。The one-dimensional, zero-based Array to sort

index
Int32 Int32 Int32 Int32

並べ替え対象の範囲の開始位置を示すインデックス。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

並べ替え対象の範囲内にある要素の数。The number of elements in the range to sort.

例外

index は、array の下限を下回っています。is less than the lower bound of array.

または-or- length が 0 未満です。is less than zero.

index および length では array の有効な範囲は指定されません。and length do not specify a valid range in array.

array の 1 つ以上の要素が、IComparable<T> ジェネリック インターフェイスを実装していません。One or more elements in array do not implement the IComparable<T> generic interface.

次のコード例に示します、Sort<T>(T[], Int32, Int32)ジェネリック メソッドのオーバー ロードとSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)配列内の範囲の並べ替えのジェネリック メソッドのオーバー ロードします。The following code example demonstrates the Sort<T>(T[], Int32, Int32) generic method overload and the Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overload for sorting a range in an array.

コード例では、という名前の文字列の代替の比較子を定義します。 ReverseCompare、実装、 IComparer<string> (IComparer(Of String) Visual basic でIComparer<String^>Visual c で) ジェネリック インターフェイス。The code example defines an alternative comparer for strings, named ReverseCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. 比較演算子の呼び出し、CompareTo(String)メソッドは、文字列は、低-高のではなく高から低を並べ替えられるように、比較対照値の順序を反転します。The comparer calls the CompareTo(String) method, reversing the order of the comparands so that the strings sort high-to-low instead of low-to-high.

コード例では、作成し、配列では、正確に) 後に次の 3 つの恐竜から成る、恐竜名が表示されます。The code example creates and displays an array of dinosaur names, consisting of three herbivores followed by three carnivores (tyrannosaurids, to be precise). Sort<T>(T[], Int32, Int32)ジェネリック メソッドのオーバー ロードが表示されると、配列の最後の 3 つの要素の並べ替えに使用します。The Sort<T>(T[], Int32, Int32) generic method overload is used to sort the last three elements of the array, which is then displayed. Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)ジェネリック メソッドのオーバー ロードが併用ReverseCompare最後の 3 つの要素を逆の順序で並べ替える。The Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overload is used with ReverseCompare to sort the last three elements in reverse order. 完全に混乱した恐竜が再度表示されます。The thoroughly confused dinosaurs are displayed again.

注意

呼び出し、Sort<T>(T[], IComparer<T>)BinarySearch<T>(T[], T, IComparer<T>)Visual Basic、c#、および C++ は、最初の引数の型とジェネリック型パラメーターの型を推論するため、ジェネリック メソッドの呼び出しを非ジェネリックの対応する間に違い探さないです。The calls to the Sort<T>(T[], IComparer<T>) and BinarySearch<T>(T[], T, IComparer<T>) generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first argument. 使用する場合、 Ildasm.exe (IL Disassembler)を Microsoft intermediate language (MSIL) を確認するには、ジェネリック メソッドが呼び出されることを確認できます。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

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

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
Imports System
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します。Each element within the specified range of elements in array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nlengthします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

こちらもご覧ください

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

指定した Array ジェネリック インターフェイスを使用して、IComparer<T> 内の要素範囲を並べ替えます。Sorts the elements in a range of elements in an Array using the specified IComparer<T> generic interface.

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

配列要素の型。The type of the elements of the array.

パラメーター

array
T[]

並べ替え対象となる、インデックス番号が 0 から始まる 1 次元 ArrayThe one-dimensional, zero-based Array to sort.

index
Int32 Int32 Int32 Int32

並べ替え対象の範囲の開始位置を示すインデックス。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

並べ替え対象の範囲内にある要素の数。The number of elements in the range to sort.

comparer
IComparer<T> IComparer<T> IComparer<T> IComparer<T>

要素を比較する際に使用する IComparer<T> ジェネリック インターフェイスの実装。各要素が実装する IComparable<T> ジェネリック インターフェイスを使用する場合は nullThe IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

例外

index は、array の下限を下回っています。is less than the lower bound of array.

または-or- length が 0 未満です。is less than zero.

index および length では array の有効な範囲は指定されません。and length do not specify a valid range in array.

または-or- comparer の実装により、並べ替え中にエラーが発生しました。The implementation of comparer caused an error during the sort. たとえば、comparer は、項目をそれ自体と比較したときに 0 を返さなかった可能性があります。For example, comparer might not return 0 when comparing an item with itself.

comparer null であり、array 内の 1 つまたは複数の要素によって IComparable<T> ジェネリック インターフェイスが実装されていません。is null, and one or more elements in array do not implement the IComparable<T> generic interface.

次のコード例に示します、Sort<T>(T[], Int32, Int32)ジェネリック メソッドのオーバー ロードとSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)配列内の範囲の並べ替えのジェネリック メソッドのオーバー ロードします。The following code example demonstrates the Sort<T>(T[], Int32, Int32) generic method overload and the Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overload for sorting a range in an array.

コード例では、という名前の文字列の代替の比較子を定義します。 ReverseCompare、実装、 IComparer<string> (IComparer(Of String) Visual basic でIComparer<String^>Visual c で) ジェネリック インターフェイス。The code example defines an alternative comparer for strings, named ReverseCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. 比較演算子の呼び出し、CompareTo(String)メソッドは、文字列は、低-高のではなく高から低を並べ替えられるように、比較対照値の順序を反転します。The comparer calls the CompareTo(String) method, reversing the order of the comparands so that the strings sort high-to-low instead of low-to-high.

コード例では、作成し、配列では、正確に) 後に次の 3 つの恐竜から成る、恐竜名が表示されます。The code example creates and displays an array of dinosaur names, consisting of three herbivores followed by three carnivores (tyrannosaurids, to be precise). Sort<T>(T[], Int32, Int32)ジェネリック メソッドのオーバー ロードが表示されると、配列の最後の 3 つの要素の並べ替えに使用します。The Sort<T>(T[], Int32, Int32) generic method overload is used to sort the last three elements of the array, which is then displayed. Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)ジェネリック メソッドのオーバー ロードが併用ReverseCompare最後の 3 つの要素を逆の順序で並べ替える。The Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overload is used with ReverseCompare to sort the last three elements in reverse order. 完全に混乱した恐竜が再度表示されます。The thoroughly confused dinosaurs are displayed again.

注意

呼び出し、Sort<T>(T[], IComparer<T>)BinarySearch<T>(T[], T, IComparer<T>)Visual Basic、c#、および C++ は、最初の引数の型とジェネリック型パラメーターの型を推論するため、ジェネリック メソッドの呼び出しを非ジェネリックの対応する間に違い探さないです。The calls to the Sort<T>(T[], IComparer<T>) and BinarySearch<T>(T[], T, IComparer<T>) generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first argument. 使用する場合、 Ildasm.exe (IL Disassembler)を Microsoft intermediate language (MSIL) を確認するには、ジェネリック メソッドが呼び出されることを確認できます。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

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

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
Imports System
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

注釈

場合comparernull、内の要素の指定した範囲内の各要素array実装する必要があります、IComparable<T>ジェネリック インターフェイスの他のすべての要素との比較ができるようにするarrayします。If comparer is null, each element within the specified range of elements in array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nlengthします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

注意 (呼び出し元)

.NET Framework 4 と以前のバージョンは、クイック ソート アルゴリズムのみを使用します。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. クイック ソートは、状況によっては、並べ替え操作がスローされます、無効な比較演算子を識別、 IndexOutOfRangeException 、例外をスローします、ArgumentException呼び出し元の例外。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 以降では、 .NET Framework 4.5.NET Framework 4.5、ことがスローした並べ替え操作がいたことができますArgumentException挿入の並べ替えと heapsort アルゴリズムでは、無効な比較子が検出されないため、例外をスローできません。Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. ほとんどの場合、これよりも少ない 16 個の要素を配列に適用されます。For the most part, this applies to arrays with fewer than 16 elements.

こちらもご覧ください

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

2 つの Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) を、最初の Array 内のキーに基づき、各キーによって実装された IComparable<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable<T> generic interface implementation of each key.

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);
static member Sort : 'Key[] * 'Value[] -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue())

型パラメーター

TKey

キー用の配列要素の型。The type of the elements of the key array.

TValue

項目用の配列要素の型。The type of the elements of the items array.

パラメーター

keys
TKey[]

並べ替えるキーを格納している 1 次元の Array。インデックス番号が 0 から始まる必要があります。The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

keys 内のキーに対応する項目が格納された、インデックス番号が 0 から始まる 1 次元 Arraykeys だけを並べ替える場合は nullThe one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

例外

items null ではなく、keys の下限が items の下限と一致していません。is not null, and the lower bound of keys does not match the lower bound of items.

または-or- items null ではなく、keys の長さが items の長さを超えています。is not null, and the length of keys is greater than the length of items.

keysArray 内の 1 つまたは複数の要素によって IComparable<T> ジェネリック インターフェイスが実装されていません。One or more elements in the keysArray do not implement the IComparable<T> generic interface.

次のコード例に示します、 Sort<TKey,TValue>(TKey[], TValue[])Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)、およびSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)の並べ替えキーと値を表す配列のペアのジェネリック メソッドのオーバー ロードします。The following code example demonstrates the Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), and Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overloads, for sorting pairs of arrays that represent keys and values.

コード例では、という名前の文字列の代替の比較子を定義します。 ReverseCompare、実装、 IComparer<string> (IComparer(Of String) Visual basic でIComparer<String^>Visual c で) ジェネリック インターフェイス。The code example defines an alternative comparer for strings, named ReverseCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. 比較演算子の呼び出し、CompareTo(String)メソッドは、文字列は、低-高のではなく高から低を並べ替えられるように、比較対照値の順序を反転します。The comparer calls the CompareTo(String) method, reversing the order of the comparands so that the strings sort high-to-low instead of low-to-high.

コード例では、作成し、恐竜の名前 (キー) の配列と各恐竜 (値) のメートル単位の最大長を表す整数の配列が表示されます。The code example creates and displays an array of dinosaur names (the keys) and an array of integers representing the maximum length of each dinosaur in meters (the values). アレイは、並べ替えし、複数回表示されます。The arrays are then sorted and displayed several times:

注意

ジェネリック メソッドの呼び出しを探さない、対応する非への呼び出しから、さまざまな Visual Basic、c#、および C++ 最初の 2 つの引数の型からのジェネリック型パラメーターの型を推論するためです。The calls to the generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first two arguments. 使用する場合、 Ildasm.exe (IL Disassembler)を Microsoft intermediate language (MSIL) を確認するには、ジェネリック メソッドが呼び出されることを確認できます。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

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

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
Imports System
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します。Each key in the keysArray has a corresponding item in the itemsArray. 並べ替え、対応する項目の中に、キーが移動したときに、itemsArray同様の位置を変更します。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. そのため、itemsArrayが内の対応するキーの並べ替えに従って並び替え、keysArrayします。Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

各キーに、keysArray実装する必要があります、IComparable<T>ジェネリック インターフェイスとその他のすべてのキーの比較ができるようにします。Each key in the keysArray must implement the IComparable<T> generic interface to be capable of comparisons with every other key.

キーよりも項目がありますが、対応するキーのない項目が並べ替えられていない場合は並べ替えることができます。You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. 項目よりも多くのキーがある場合に並べ替えることはできません。スローされること、ArgumentExceptionします。You cannot sort if there are more keys than items; doing this throws an ArgumentException.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nは、Lengtharrayします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

こちらもご覧ください

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

2 つの Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) を、最初の Array 内のキーに基づき、指定した IComparer<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer<T> generic interface.

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

キー用の配列要素の型。The type of the elements of the key array.

TValue

項目用の配列要素の型。The type of the elements of the items array.

パラメーター

keys
TKey[]

並べ替えるキーを格納している 1 次元の Array。インデックス番号が 0 から始まる必要があります。The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

keys 内のキーに対応する項目が格納された、インデックス番号が 0 から始まる 1 次元 Arraykeys だけを並べ替える場合は nullThe one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

comparer
IComparer<TKey>

要素を比較する際に使用する IComparer<T> ジェネリック インターフェイスの実装。各要素が実装する IComparable<T> ジェネリック インターフェイスを使用する場合は nullThe IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

例外

items null ではなく、keys の下限が items の下限と一致していません。is not null, and the lower bound of keys does not match the lower bound of items.

または-or- items null ではなく、keys の長さが items の長さを超えています。is not null, and the length of keys is greater than the length of items.

または-or- comparer の実装により、並べ替え中にエラーが発生しました。The implementation of comparer caused an error during the sort. たとえば、comparer は、項目をそれ自体と比較したときに 0 を返さなかった可能性があります。For example, comparer might not return 0 when comparing an item with itself.

comparer null であり、keysArray 内の 1 つまたは複数の要素によって IComparable<T> ジェネリック インターフェイスが実装されていません。is null, and one or more elements in the keysArray do not implement the IComparable<T> generic interface.

次のコード例に示します、 Sort<TKey,TValue>(TKey[], TValue[])、[]、TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Collections.Generic.IComparer%7B%60%600%7D%29 >、Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)の並べ替えキーと値を表す配列のペアのジェネリック メソッドのオーバー ロードします。The following code example demonstrates the Sort<TKey,TValue>(TKey[], TValue[]), [], TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Collections.Generic.IComparer%7B%60%600%7D%29>,Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), and Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overloads, for sorting pairs of arrays that represent keys and values.

コード例では、という名前の文字列の代替の比較子を定義します。 ReverseCompare、実装、 IComparer<string> (IComparer(Of String) Visual basic でIComparer<String^>Visual c で) ジェネリック インターフェイス。The code example defines an alternative comparer for strings, named ReverseCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. 比較演算子の呼び出し、CompareTo(String)メソッドは、文字列は、低-高のではなく高から低を並べ替えられるように、比較対照値の順序を反転します。The comparer calls the CompareTo(String) method, reversing the order of the comparands so that the strings sort high-to-low instead of low-to-high.

コード例では、作成し、恐竜の名前 (キー) の配列と各恐竜 (値) のメートル単位の最大長を表す整数の配列が表示されます。The code example creates and displays an array of dinosaur names (the keys) and an array of integers representing the maximum length of each dinosaur in meters (the values). アレイは、並べ替えし、複数回表示されます。The arrays are then sorted and displayed several times:

注意

ジェネリック メソッドの呼び出しを探さない、対応する非への呼び出しから、さまざまな Visual Basic、c#、および C++ 最初の 2 つの引数の型からのジェネリック型パラメーターの型を推論するためです。The calls to the generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first two arguments. 使用する場合、 Ildasm.exe (IL Disassembler)を Microsoft intermediate language (MSIL) を確認するには、ジェネリック メソッドが呼び出されることを確認できます。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

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

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
Imports System
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します。Each key in the keysArray has a corresponding item in the itemsArray. 並べ替え、対応する項目の中に、キーが移動したときに、itemsArray同様の位置を変更します。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. そのため、itemsArrayが内の対応するキーの並べ替えに従って並び替え、keysArrayします。Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

場合comparernull、それぞれのキー、keysArray実装する必要があります、IComparable<T>ジェネリック インターフェイスとその他のすべてのキーの比較ができるようにします。If comparer is null, each key in the keysArray must implement the IComparable<T> generic interface to be capable of comparisons with every other key.

キーよりも項目がありますが、対応するキーのない項目が並べ替えられていない場合は並べ替えることができます。You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. 項目よりも多くのキーがある場合に並べ替えることはできません。スローされること、ArgumentExceptionします。You cannot sort if there are more keys than items; doing this throws an ArgumentException.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nは、Lengtharrayします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

注意 (呼び出し元)

.NET Framework 4 と以前のバージョンは、クイック ソート アルゴリズムのみを使用します。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. クイック ソートは、状況によっては、並べ替え操作がスローされます、無効な比較演算子を識別、 IndexOutOfRangeException 、例外をスローします、ArgumentException呼び出し元の例外。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 以降では、 .NET Framework 4.5.NET Framework 4.5、ことがスローした並べ替え操作がいたことができますArgumentException挿入の並べ替えと heapsort アルゴリズムでは、無効な比較子が検出されないため、例外をスローできません。Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. ほとんどの場合、これよりも少ない 16 個の要素を配列に適用されます。For the most part, this applies to arrays with fewer than 16 elements.

こちらもご覧ください

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

2 つの Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) の要素範囲を、最初の Array 内のキーに基づき、各キーによって実装された IComparable<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts a range of elements in a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable<T> generic interface implementation of each key.

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

キー用の配列要素の型。The type of the elements of the key array.

TValue

項目用の配列要素の型。The type of the elements of the items array.

パラメーター

keys
TKey[]

並べ替えるキーを格納している 1 次元の Array。インデックス番号が 0 から始まる必要があります。The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

keys 内のキーに対応する項目が格納された、インデックス番号が 0 から始まる 1 次元 Arraykeys だけを並べ替える場合は nullThe one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

index
Int32 Int32 Int32 Int32

並べ替え対象の範囲の開始位置を示すインデックス。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

並べ替え対象の範囲内にある要素の数。The number of elements in the range to sort.

例外

index keys の下限を下回っています。is less than the lower bound of keys.

または-or- length が 0 未満です。is less than zero.

items null ではなく、keys の下限が items の下限と一致していません。is not null, and the lower bound of keys does not match the lower bound of items.

または-or- items null ではなく、keys の長さが items の長さを超えています。is not null, and the length of keys is greater than the length of items.

または-or- index および length によって keysArray 内の有効な範囲が指定されていません。and length do not specify a valid range in the keysArray.

または-or- items null ではなく、index および length によって itemsArray 内の有効な範囲が指定されていません。is not null, and index and length do not specify a valid range in the itemsArray.

keysArray 内の 1 つまたは複数の要素によって IComparable<T> ジェネリック インターフェイスが実装されていません。One or more elements in the keysArray do not implement the IComparable<T> generic interface.

次のコード例に示します、 Sort<TKey,TValue>(TKey[], TValue[])Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)、[]、TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Int32%2CSystem.Int32%29 >、およびSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)ジェネリック メソッドのオーバー ロード、並べ替えキーと値を表す配列のペア。The following code example demonstrates the Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), [], TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Int32%2CSystem.Int32%29>, and Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overloads, for sorting pairs of arrays that represent keys and values.

コード例では、という名前の文字列の代替の比較子を定義します。 ReverseCompare、実装、 IComparer<string> (IComparer(Of String) Visual basic でIComparer<String^>Visual c で) ジェネリック インターフェイス。The code example defines an alternative comparer for strings, named ReverseCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. 比較演算子の呼び出し、CompareTo(String)メソッドは、文字列は、低-高のではなく高から低を並べ替えられるように、比較対照値の順序を反転します。The comparer calls the CompareTo(String) method, reversing the order of the comparands so that the strings sort high-to-low instead of low-to-high.

コード例では、作成し、恐竜の名前 (キー) の配列と各恐竜 (値) のメートル単位の最大長を表す整数の配列が表示されます。The code example creates and displays an array of dinosaur names (the keys) and an array of integers representing the maximum length of each dinosaur in meters (the values). アレイは、並べ替えし、複数回表示されます。The arrays are then sorted and displayed several times:

注意

ジェネリック メソッドの呼び出しを探さない、対応する非への呼び出しから、さまざまな Visual Basic、c#、および C++ 最初の 2 つの引数の型からのジェネリック型パラメーターの型を推論するためです。The calls to the generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first two arguments. 使用する場合、 Ildasm.exe (IL Disassembler)を Microsoft intermediate language (MSIL) を確認するには、ジェネリック メソッドが呼び出されることを確認できます。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

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

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
Imports System
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します。Each key in the keysArray has a corresponding item in the itemsArray. 並べ替え、対応する項目の中に、キーが移動したときに、itemsArray同様の位置を変更します。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. そのため、itemsArrayが内の対応するキーの並べ替えに従って並び替え、keysArrayします。Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

指定した範囲内の要素の各キー、keysArray実装する必要があります、IComparable<T>ジェネリック インターフェイスとその他のすべてのキーの比較ができるようにします。Each key within the specified range of elements in the keysArray must implement the IComparable<T> generic interface to be capable of comparisons with every other key.

キーよりも項目がありますが、対応するキーのない項目が並べ替えられていない場合は並べ替えることができます。You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. 項目よりも多くのキーがある場合に並べ替えることはできません。スローされること、ArgumentExceptionします。You cannot sort if there are more keys than items; doing this throws an ArgumentException.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nlengthします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

こちらもご覧ください

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

2 つの Array オブジェクト (一方のオブジェクトがキーを格納し、他方のオブジェクトがそれらに対応する項目を格納する) 内の要素範囲を、最初の Array 内のキーに基づき、指定した IComparer<T> ジェネリック インターフェイスを使用して並べ替えます。Sorts a range of elements in a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer<T> generic interface.

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

キー用の配列要素の型。The type of the elements of the key array.

TValue

項目用の配列要素の型。The type of the elements of the items array.

パラメーター

keys
TKey[]

並べ替えるキーを格納している 1 次元の Array。インデックス番号が 0 から始まる必要があります。The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

keys 内のキーに対応する項目が格納された、インデックス番号が 0 から始まる 1 次元 Arraykeys だけを並べ替える場合は nullThe one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

index
Int32 Int32 Int32 Int32

並べ替え対象の範囲の開始位置を示すインデックス。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

並べ替え対象の範囲内にある要素の数。The number of elements in the range to sort.

comparer
IComparer<TKey>

要素を比較する際に使用する IComparer<T> ジェネリック インターフェイスの実装。各要素が実装する IComparable<T> ジェネリック インターフェイスを使用する場合は nullThe IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

例外

index keys の下限を下回っています。is less than the lower bound of keys.

または-or- length が 0 未満です。is less than zero.

items null ではなく、keys の下限が items の下限と一致していません。is not null, and the lower bound of keys does not match the lower bound of items.

または-or- items null ではなく、keys の長さが items の長さを超えています。is not null, and the length of keys is greater than the length of items.

または-or- index および length によって keysArray 内の有効な範囲が指定されていません。and length do not specify a valid range in the keysArray.

または-or- items null ではなく、index および length によって itemsArray 内の有効な範囲が指定されていません。is not null, and index and length do not specify a valid range in the itemsArray.

または-or- comparer の実装により、並べ替え中にエラーが発生しました。The implementation of comparer caused an error during the sort. たとえば、comparer は、項目をそれ自体と比較したときに 0 を返さなかった可能性があります。For example, comparer might not return 0 when comparing an item with itself.

comparer null であり、keysArray 内の 1 つまたは複数の要素によって IComparable<T> ジェネリック インターフェイスが実装されていません。is null, and one or more elements in the keysArray do not implement the IComparable<T> generic interface.

次のコード例に示します、 Sort<TKey,TValue>(TKey[], TValue[])Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)、および []、TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Int32%2CSystem.Int32%2CSystem.Collections.Generic.IComparer%7B%60%600%7D%29 > ペアのキーと値を表す配列を並べ替えるためのジェネリック メソッドのオーバー ロードします。The following code example demonstrates the Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), and [], TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Int32%2CSystem.Int32%2CSystem.Collections.Generic.IComparer%7B%60%600%7D%29> generic method overloads, for sorting pairs of arrays that represent keys and values.

コード例では、という名前の文字列の代替の比較子を定義します。 ReverseCompare、実装、 IComparer<string>(IComparer(Of String) Visual basic でIComparer<String^>Visual c で) ジェネリック インターフェイス。The code example defines an alternative comparer for strings, named ReverseCompare, which implements the IComparer<string>(IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. 比較演算子の呼び出し、CompareTo(String)メソッドは、文字列は、低-高のではなく高から低を並べ替えられるように、比較対照値の順序を反転します。The comparer calls the CompareTo(String) method, reversing the order of the comparands so that the strings sort high-to-low instead of low-to-high.

コード例では、作成し、恐竜の名前 (キー) の配列と各恐竜 (値) のメートル単位の最大長を表す整数の配列が表示されます。The code example creates and displays an array of dinosaur names (the keys) and an array of integers representing the maximum length of each dinosaur in meters (the values). アレイは、並べ替えし、複数回表示されます。The arrays are then sorted and displayed several times:

  • Sort<TKey,TValue>(TKey[], TValue[])オーバー ロードは、最初の配列での恐竜名の順序で両方の配列の並べ替えに使用します。The Sort<TKey,TValue>(TKey[], TValue[]) overload is used to sort both arrays in order of the dinosaur names in the first array.

  • Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)オーバー ロードのインスタンスおよびReverseCompareペアの配列の並べ替え順序を反転させるために使用します。The Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) overload and an instance of ReverseCompare are used to reverse the sort order of the paired arrays.

  • Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)オーバー ロードが両方の配列の最後の 3 つの要素の並べ替えに使用します。The Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) overload is used to sort the last three elements of both arrays.

  • []、TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Int32%2CSystem.Int32%2CSystem.Collections.Generic.IComparer%7B%60%600%7D%29 > オーバー ロードは最後の 3 つの並べ替えに使用逆の順序で両方の要素を配列します。The [], TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Int32%2CSystem.Int32%2CSystem.Collections.Generic.IComparer%7B%60%600%7D%29> overload is used to sort the last three elements of both arrays in reverse order.

注意

ジェネリック メソッドの呼び出しを探さない、対応する非への呼び出しから、さまざまな Visual Basic、c#、および C++ 最初の 2 つの引数の型からのジェネリック型パラメーターの型を推論するためです。The calls to the generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first two arguments. 使用する場合、 Ildasm.exe (IL Disassembler)を Microsoft intermediate language (MSIL) を確認するには、ジェネリック メソッドが呼び出されることを確認できます。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

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

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
Imports System
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します。Each key in the keysArray has a corresponding item in the itemsArray. 並べ替え、対応する項目の中に、キーが移動したときに、itemsArray同様の位置を変更します。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. そのため、itemsArrayが内の対応するキーの並べ替えに従って並び替え、keysArrayします。Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

場合comparernull、内の要素の指定された範囲内の各キー、keysArray実装する必要があります、IComparable<T>ジェネリック インターフェイスとその他のすべてのキーの比較ができるようにします。If comparer is null, each key within the specified range of elements in the keysArray must implement the IComparable<T> generic interface to be capable of comparisons with every other key.

キーよりも項目がありますが、対応するキーのない項目が並べ替えられていない場合は並べ替えることができます。You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. 項目よりも多くのキーがある場合に並べ替えることはできません。スローされること、ArgumentExceptionします。You cannot sort if there are more keys than items; doing this throws an ArgumentException.

並べ替えが正常に完了していない場合、結果は未定義です。If the sort is not successfully completed, the results are undefined.

このメソッドは、とおり内省的で並べ替え (introsort) アルゴリズムを使用します。This method uses the introspective sort (introsort) algorithm as follows:

  • パーティションのサイズが 16 個未満の要素の場合は、使用して、挿入ソートアルゴリズム。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • パーティションの数が 2 を超える場合 * ログNここで、 N範囲は、使用して、入力配列のHeapsortアルゴリズム。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • それ以外の場合、使用して、クイック ソートアルゴリズム。Otherwise, it uses a Quicksort algorithm.

この実装は、不安定な並べ替えを実行します。2 つの要素が等しい場合は、その順序は保持されない可能性があります。This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. これに対し、安定した並べ替えが等しい要素の順序が保持されます。In contrast, a stable sort preserves the order of elements that are equal.

最悪の場合、Heapsort とクイック ソート アルゴリズムを使用して並べ替えた配列の場合は、このメソッドは、O (nログn) 操作、nlengthします。For arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

注意 (呼び出し元)

.NET Framework 4 と以前のバージョンは、クイック ソート アルゴリズムのみを使用します。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. クイック ソートは、状況によっては、並べ替え操作がスローされます、無効な比較演算子を識別、 IndexOutOfRangeException 、例外をスローします、ArgumentException呼び出し元の例外。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 以降では、 .NET Framework 4.5.NET Framework 4.5、ことがスローした並べ替え操作がいたことができますArgumentException挿入の並べ替えと heapsort アルゴリズムでは、無効な比較子が検出されないため、例外をスローできません。Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. ほとんどの場合、これよりも少ない 16 個の要素を配列に適用されます。For the most part, this applies to arrays with fewer than 16 elements.

こちらもご覧ください

適用対象