Array.Sort Méthode

Définition

Trie les éléments dans un tableau unidimensionnel.Sorts the elements in a one-dimensional array.

Surcharges

Sort(Array, Int32, Int32, IComparer)

Trie les éléments d’une plage d’éléments d’un Array unidimensionnel à l’aide du IComparer spécifié.Sorts the elements in a range of elements in a one-dimensional Array using the specified IComparer.

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

Trie une plage d’éléments dans une paire d’objets Array unidimensionnels (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’objet IComparer spécifié.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)

Trie les éléments d’une plage d’éléments d’un Array unidimensionnel à l’aide de l’implémentation IComparable de chaque élément de l’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)

Trie une plage d’éléments dans une paire d’objets Array unidimensionnels (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’implémentation IComparable de chaque clé.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)

Trie les éléments d’un Array unidimensionnel à l’aide de l’objet IComparer spécifié.Sorts the elements in a one-dimensional Array using the specified IComparer.

Sort(Array, Array, IComparer)

Trie une paire d’objets Array unidimensionnels (l’un contient les clés et l’autre les éléments correspondants) en fonction des clés du premier Array à l’aide de l’objet IComparer spécifié.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)

Trie une paire d’objets Array unidimensionnels (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’implémentation de IComparable de chaque clé.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)

Trie les éléments dans l’intégralité d’un Array unidimensionnel à l’aide de l’implémentation IComparable de chaque élément du Array.Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.

Sort<T>(T[])

Trie les éléments dans l’intégralité d’un Array à l’aide de l’implémentation de l’interface générique IComparable<T> de chaque élément du 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>)

Trie les éléments dans un Array à l’aide de l’interface générique IComparer<T> spécifiée.Sorts the elements in an Array using the specified IComparer<T> generic interface.

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

Trie les éléments inclus dans un Array à l’aide de l’objet Comparison<T> spécifié.Sorts the elements in an Array using the specified Comparison<T>.

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

Trie les éléments d’une plage d’éléments d’un Array à l’aide de l’implémentation de l’interface générique IComparable<T> de chaque élément de 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>)

Trie les éléments d’une plage d’éléments dans un Array à l’aide de l’interface générique IComparer<T> spécifiée.Sorts the elements in a range of elements in an Array using the specified IComparer<T> generic interface.

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

Trie une paire d’objets Array (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’implémentation de l’interface générique IComparable<T> de chaque clé.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>)

Trie une paire d’objets Array (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’interface générique IComparer<T> spécifiée.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)

Trie une plage d’éléments dans une paire d’objets Array (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’implémentation d’interface générique IComparable<T> de chaque clé.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>)

Trie une plage d’éléments dans une paire d’objets Array (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’interface générique IComparer<T> spécifiée.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)

Trie les éléments d’une plage d’éléments d’un Array unidimensionnel à l’aide du IComparer spécifié.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

Paramètres

array
Array

Array unidimensionnel à trier.The one-dimensional Array to sort.

index
Int32

Index de départ de la plage à trier.The starting index of the range to sort.

length
Int32

Nombre d'éléments à trier dans la plage.The number of elements in the range to sort.

comparer
IComparer

Implémentation de IComparer à utiliser pendant la comparaison d'éléments.The IComparer implementation to use when comparing elements.

- ou --or- null pour utiliser l’implémentation de IComparable de chaque élément.null to use the IComparable implementation of each element.

Exceptions

array est null.array is null.

array est multidimensionnel.array is multidimensional.

index est inférieur à la limite inférieure d’array.index is less than the lower bound of array.

- ou --or- length est inférieur à zéro.length is less than zero.

index et length ne spécifient pas une plage valide dans array.index and length do not specify a valid range in array.

- ou --or- L’implémentation de comparer a provoqué une erreur pendant le tri.The implementation of comparer caused an error during the sort. Par exemple, comparer peut ne pas retourner 0 pendant la comparaison d’un élément à lui-même.For example, comparer might not return 0 when comparing an item with itself.

comparer a la valeur null, et un ou plusieurs éléments de array n’implémentent pas l’interface IComparablecomparer is null, and one or more elements in array do not implement the IComparable interface.

Exemples

L’exemple de code suivant montre comment trier les valeurs d’un Array à l’aide du comparateur par défaut et d’un comparateur personnalisé qui inverse l’ordre de tri.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. Notez que le résultat peut varier en fonction du CultureInfoactuel.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

Remarques

Si comparer est null, chaque élément de la plage spécifiée d’éléments dans array doit implémenter l’interface IComparable pour pouvoir effectuer des comparaisons avec chaque autre élément dans 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.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Le .NET Framework comprend des implémentations prédéfinies de IComparer, présentées dans le tableau suivant.The .NET Framework includes predefined IComparer implementations listed in the following table.

ImplémentationImplementation DescriptionDescription
System.Collections.CaseInsensitiveComparer Compare deux objets quelconques, mais effectue une comparaison de chaînes ne respectant pas la casse.Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default Compare deux objets à l’aide des conventions de tri de la culture actuelle.Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant Compare deux objets à l’aide des conventions de tri de la culture dite indifférente.Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default Compare deux objets de type T à l’aide de l’ordre de tri par défaut du type.Compares two objects of type T by using the type's default sort order.

Vous pouvez également prendre en charge les comparaisons personnalisées en fournissant une instance de votre propre implémentation de IComparer au paramètre comparer.You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. L’exemple fait cela en définissant une classe ReverseComparer qui inverse l’ordre de tri par défaut pour les instances d’un type et effectue une comparaison de chaînes ne respectant pas la casse.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.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est length.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.

Notes pour les appelants

Le .NET Framework 4 et les versions antérieures utilisaient uniquement l’algorithme tri rapide.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Tri rapide identifie les comparateurs non valides dans certaines situations où l’opération de tri lève une exception IndexOutOfRangeException et lève une exception ArgumentException à l’appelant.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. À partir du .NET Framework 4.5.NET Framework 4.5, il est possible que les opérations de tri qui ont précédemment levé ArgumentException ne lèvent pas d’exception, car les algorithmes de tri et d’insertion HeapSort ne détectent pas un comparateur non valide.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. Pour l’essentiel, cela s’applique aux tableaux avec moins ou égal à 16 éléments.For the most part, this applies to arrays with less than or equal to 16 elements.

Voir aussi

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

Trie une plage d’éléments dans une paire d’objets Array unidimensionnels (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’objet IComparer spécifié.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)

Paramètres

keys
Array

Array unidimensionnel qui contient les clés à trier.The one-dimensional Array that contains the keys to sort.

items
Array

Array unidimensionnel qui contient les éléments correspondant à chaque clé du keysArray.The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

- ou --or- null pour trier uniquement keysArray.null to sort only the keysArray.

index
Int32

Index de départ de la plage à trier.The starting index of the range to sort.

length
Int32

Nombre d'éléments à trier dans la plage.The number of elements in the range to sort.

comparer
IComparer

Implémentation de IComparer à utiliser pendant la comparaison d'éléments.The IComparer implementation to use when comparing elements.

- ou --or- null pour utiliser l’implémentation de IComparable de chaque élément.null to use the IComparable implementation of each element.

Exceptions

keys a la valeur null.keys is null.

keysArray est multidimensionnel.The keysArray is multidimensional.

- ou --or- itemsArray est multidimensionnel.The itemsArray is multidimensional.

index est inférieur à la limite inférieure d’keys.index is less than the lower bound of keys.

- ou --or- length est inférieur à zéro.length is less than zero.

items n’est pas null, et la limite inférieure de keys ne correspond pas à la limite inférieure de items.items is not null, and the lower bound of keys does not match the lower bound of items.

- ou --or- items n’est pas null, et la longueur de keys est supérieure à la longueur d’items.items is not null, and the length of keys is greater than the length of items.

- ou --or- index et length ne spécifient pas une plage valide dans keysArray.index and length do not specify a valid range in the keysArray.

- ou --or- items n’est pas null, et index et length ne spécifient pas une plage valide dans itemsArray.items is not null, and index and length do not specify a valid range in the itemsArray.

- ou --or- L’implémentation de comparer a provoqué une erreur pendant le tri.The implementation of comparer caused an error during the sort. Par exemple, comparer peut ne pas retourner 0 pendant la comparaison d’un élément à lui-même.For example, comparer might not return 0 when comparing an item with itself.

comparer est null, et un ou plusieurs éléments de keysArray n’implémentent pas l’interface IComparable.comparer is null, and one or more elements in the keysArray do not implement the IComparable interface.

Exemples

L’exemple de code suivant montre comment trier deux tableaux associés où le premier tableau contient les clés et le second contient les valeurs.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. Les tris sont effectués à l’aide du comparateur par défaut et d’un comparateur personnalisé qui inverse l’ordre de tri.Sorts are done using the default comparer and a custom comparer that reverses the sort order. Notez que le résultat peut varier en fonction du CultureInfoactuel.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.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub


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

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

   End Sub

End Class


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

Remarques

Chaque clé de la keysArray a un élément correspondant dans leArrayitems.Each key in the keysArray has a corresponding item in the itemsArray. Quand une clé est repositionnée pendant le tri, l’élément correspondant dans la itemsArray est repositionné de manière similaire.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Par conséquent, le itemsArray est trié en fonction de la disposition des clés correspondantes dans leArraykeys.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Si comparer est null, chaque clé de la plage spécifiée d’éléments dans leArray de keysdoit implémenter l’interface IComparable pour pouvoir effectuer des comparaisons avec chaque autre clé.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.

Vous pouvez trier s’il y a plus d’éléments que de clés, mais les éléments qui n’ont pas de clés correspondantes ne seront pas triés.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. Vous ne pouvez pas trier s’il y a plus de clés que d’éléments ; Cela lève une ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Le .NET Framework comprend des implémentations prédéfinies de IComparer, présentées dans le tableau suivant.The .NET Framework includes predefined IComparer implementations listed in the following table.

ImplémentationImplementation DescriptionDescription
System.Collections.CaseInsensitiveComparer Compare deux objets quelconques, mais effectue une comparaison de chaînes ne respectant pas la casse.Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default Compare deux objets à l’aide des conventions de tri de la culture actuelle.Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant Compare deux objets à l’aide des conventions de tri de la culture dite indifférente.Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default Compare deux objets de type T à l’aide de l’ordre de tri par défaut du type.Compares two objects of type T by using the type's default sort order.

Vous pouvez également prendre en charge les comparaisons personnalisées en fournissant une instance de votre propre implémentation de IComparer au paramètre comparer.You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. L’exemple fait cela en définissant une implémentation IComparer personnalisée qui inverse l’ordre de tri par défaut et effectue une comparaison de chaînes ne respectant pas la casse.The example does this by defining a custom IComparer implementation that reverses the default sort order and performs case-insensitive string comparison.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est length.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.

Notes pour les appelants

Le .NET Framework 4 et les versions antérieures utilisaient uniquement l’algorithme tri rapide.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Tri rapide identifie les comparateurs non valides dans certaines situations où l’opération de tri lève une exception IndexOutOfRangeException et lève une exception ArgumentException à l’appelant.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. À partir du .NET Framework 4.5.NET Framework 4.5, il est possible que les opérations de tri qui ont précédemment levé ArgumentException ne lèvent pas d’exception, car les algorithmes de tri et d’insertion HeapSort ne détectent pas un comparateur non valide.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. Pour l’essentiel, cela s’applique aux tableaux avec moins ou égal à 16 éléments.For the most part, this applies to arrays with less than or equal to 16 elements.

Voir aussi

Sort(Array, Int32, Int32)

Trie les éléments d’une plage d’éléments d’un Array unidimensionnel à l’aide de l’implémentation IComparable de chaque élément de l’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

Paramètres

array
Array

Array unidimensionnel à trier.The one-dimensional Array to sort.

index
Int32

Index de départ de la plage à trier.The starting index of the range to sort.

length
Int32

Nombre d'éléments à trier dans la plage.The number of elements in the range to sort.

Exceptions

array a la valeur null.array is null.

array est multidimensionnel.array is multidimensional.

index est inférieur à la limite inférieure d’array.index is less than the lower bound of array.

- ou --or- length est inférieur à zéro.length is less than zero.

index et length ne spécifient pas une plage valide dans array.index and length do not specify a valid range in array.

Un ou plusieurs éléments de array n’implémentent pas l’interface IComparable.One or more elements in array do not implement the IComparable interface.

Exemples

L’exemple de code suivant montre comment trier les valeurs d’un Array à l’aide du comparateur par défaut et d’un comparateur personnalisé qui inverse l’ordre de tri.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. Notez que le résultat peut varier en fonction du CultureInfoactuel.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

Remarques

Chaque élément dans la plage d’éléments spécifiée de array doit implémenter l’interface IComparable afin de pouvoir effectuer des comparaisons avec chaque autre élément dans 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.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est length.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.

Voir aussi

Sort(Array, Array, Int32, Int32)

Trie une plage d’éléments dans une paire d’objets Array unidimensionnels (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’implémentation IComparable de chaque clé.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)

Paramètres

keys
Array

Array unidimensionnel qui contient les clés à trier.The one-dimensional Array that contains the keys to sort.

items
Array

Array unidimensionnel qui contient les éléments correspondant à chaque clé du keysArray.The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

- ou --or- null pour trier uniquement keysArray.null to sort only the keysArray.

index
Int32

Index de départ de la plage à trier.The starting index of the range to sort.

length
Int32

Nombre d'éléments à trier dans la plage.The number of elements in the range to sort.

Exceptions

keys a la valeur null.keys is null.

keysArray est multidimensionnel.The keysArray is multidimensional.

- ou --or- itemsArray est multidimensionnel.The itemsArray is multidimensional.

index est inférieur à la limite inférieure d’keys.index is less than the lower bound of keys.

- ou --or- length est inférieur à zéro.length is less than zero.

items n’est pas null, et la longueur de keys est supérieure à la longueur de items.items is not null, and the length of keys is greater than the length of items.

- ou --or- index et length ne spécifient pas une plage valide dans keysArray.index and length do not specify a valid range in the keysArray.

- ou --or- items n’est pas null, et index et length ne spécifient pas une plage valide dans itemsArray.items is not null, and index and length do not specify a valid range in the itemsArray.

Un ou plusieurs éléments de keysArray n’implémentent pas l’interface IComparable.One or more elements in the keysArray do not implement the IComparable interface.

Exemples

L’exemple de code suivant montre comment trier deux tableaux associés où le premier tableau contient les clés et le second contient les valeurs.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. Les tris sont effectués à l’aide du comparateur par défaut et d’un comparateur personnalisé qui inverse l’ordre de tri.Sorts are done using the default comparer and a custom comparer that reverses the sort order. Notez que le résultat peut varier en fonction du CultureInfoactuel.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.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub


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

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

   End Sub

End Class


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

Remarques

Chaque clé de la keysArray a un élément correspondant dans leArrayitems.Each key in the keysArray has a corresponding item in the itemsArray. Quand une clé est repositionnée pendant le tri, l’élément correspondant dans la itemsArray est repositionné de manière similaire.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Par conséquent, le itemsArray est trié en fonction de la disposition des clés correspondantes dans leArraykeys.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Chaque clé dans la plage spécifiée d’éléments dans leArray keysdoit implémenter l’interface IComparable pour pouvoir effectuer des comparaisons avec chaque autre clé.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.

Vous pouvez trier s’il y a plus d’éléments que de clés, mais les éléments qui n’ont pas de clés correspondantes ne seront pas triés.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. Vous ne pouvez pas trier s’il y a plus de clés que d’éléments ; Cela lève une ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est length.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.

Voir aussi

Sort(Array, IComparer)

Trie les éléments d’un Array unidimensionnel à l’aide de l’objet IComparer spécifié.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

Paramètres

array
Array

Tableau unidimensionnel à trier.The one-dimensional array to sort.

comparer
IComparer

Implémentation à utiliser pendant la comparaison d’éléments.The implementation to use when comparing elements.

- ou --or- null pour utiliser l’implémentation de IComparable de chaque élément.null to use the IComparable implementation of each element.

Exceptions

array est null.array is null.

array est multidimensionnel.array is multidimensional.

comparer a la valeur null, et un ou plusieurs éléments de array n’implémentent pas l’interface IComparablecomparer is null, and one or more elements in array do not implement the IComparable interface.

L’implémentation de comparer a provoqué une erreur pendant le tri.The implementation of comparer caused an error during the sort. Par exemple, comparer peut ne pas retourner 0 pendant la comparaison d’un élément à lui-même.For example, comparer might not return 0 when comparing an item with itself.

Exemples

L’exemple suivant trie les valeurs d’un tableau de chaînes à l’aide du comparateur par défaut.The following example sorts the values in a string array by using the default comparer. Il définit également une implémentation IComparer personnalisée nommée ReverseComparer qui inverse l’ordre de tri par défaut d’un objet lors de l’exécution d’une comparaison de chaînes ne respectant pas la casse.It also defines a custom IComparer implementation named ReverseComparer that reverses an object's default sort order while performing a case-insensitive string comparison. Notez que la sortie peut varier en fonction de la culture actuelle.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

Remarques

Si comparer est null, chaque élément de array doit implémenter l’interface IComparable pour pouvoir effectuer des comparaisons avec chaque autre élément dans 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.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est le Length de array.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.

Le .NET Framework comprend des implémentations prédéfinies de IComparer, présentées dans le tableau suivant.The .NET Framework includes predefined IComparer implementations listed in the following table.

ImplémentationImplementation DescriptionDescription
System.Collections.CaseInsensitiveComparer Compare deux objets quelconques, mais effectue une comparaison de chaînes ne respectant pas la casse.Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default Compare deux objets à l’aide des conventions de tri de la culture actuelle.Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant Compare deux objets à l’aide des conventions de tri de la culture dite indifférente.Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default Compare deux objets de type T à l’aide de l’ordre de tri par défaut du type.Compares two objects of type T by using the type's default sort order.

Vous pouvez également prendre en charge les comparaisons personnalisées en fournissant une instance de votre propre implémentation de IComparer au paramètre comparer.You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. L’exemple fait cela en définissant une classe ReverseComparer qui inverse l’ordre de tri par défaut pour les instances d’un type et effectue une comparaison de chaînes ne respectant pas la casse.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.

Notes pour les appelants

Le .NET Framework 4 et les versions antérieures utilisaient uniquement l’algorithme tri rapide.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Tri rapide identifie les comparateurs non valides dans certaines situations où l’opération de tri lève une exception IndexOutOfRangeException et lève une exception ArgumentException à l’appelant.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. À partir du .NET Framework 4.5.NET Framework 4.5, il est possible que les opérations de tri qui ont précédemment levé ArgumentException ne lèvent pas d’exception, car les algorithmes de tri et d’insertion HeapSort ne détectent pas un comparateur non valide.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. Pour l’essentiel, cela s’applique aux tableaux avec moins ou égal à 16 éléments.For the most part, this applies to arrays with less than or equal to 16 elements.

Voir aussi

Sort(Array, Array, IComparer)

Trie une paire d’objets Array unidimensionnels (l’un contient les clés et l’autre les éléments correspondants) en fonction des clés du premier Array à l’aide de l’objet IComparer spécifié.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)

Paramètres

keys
Array

Array unidimensionnel qui contient les clés à trier.The one-dimensional Array that contains the keys to sort.

items
Array

Array unidimensionnel qui contient les éléments correspondant à chaque clé du keysArray.The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

- ou --or- null pour trier uniquement keysArray.null to sort only the keysArray.

comparer
IComparer

Implémentation de IComparer à utiliser pendant la comparaison d'éléments.The IComparer implementation to use when comparing elements.

- ou --or- null pour utiliser l’implémentation de IComparable de chaque élément.null to use the IComparable implementation of each element.

Exceptions

keys est null.keys is null.

keysArray est multidimensionnel.The keysArray is multidimensional.

- ou --or- itemsArray est multidimensionnel.The itemsArray is multidimensional.

items n’est pas null, et la longueur de keys est supérieure à la longueur d’items.items is not null, and the length of keys is greater than the length of items.

- ou --or- L’implémentation de comparer a provoqué une erreur pendant le tri.The implementation of comparer caused an error during the sort. Par exemple, comparer peut ne pas retourner 0 pendant la comparaison d’un élément à lui-même.For example, comparer might not return 0 when comparing an item with itself.

comparer est null, et un ou plusieurs éléments de keysArray n’implémentent pas l’interface IComparable.comparer is null, and one or more elements in the keysArray do not implement the IComparable interface.

Exemples

L’exemple suivant montre comment trier deux tableaux associés où le premier tableau contient les clés et le second contient les valeurs.The following example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. Les tris sont effectués à l’aide du comparateur par défaut et d’un comparateur personnalisé qui inverse l’ordre de tri.Sorts are done using the default comparer and a custom comparer that reverses the sort order. Notez que le résultat peut varier en fonction du CultureInfoactuel.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.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub


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

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

   End Sub

End Class


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

Remarques

Chaque clé de la keysArray a un élément correspondant dans leArrayitems.Each key in the keysArray has a corresponding item in the itemsArray. Quand une clé est repositionnée pendant le tri, l’élément correspondant dans la itemsArray est repositionné de manière similaire.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Par conséquent, le itemsArray est trié en fonction de la disposition des clés correspondantes dans leArraykeys.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Si comparer est null, chaque clé de laArray keysdoit implémenter l’interface IComparable pour pouvoir effectuer des comparaisons avec chaque autre clé.If comparer is null, each key in the keysArray must implement the IComparable interface to be capable of comparisons with every other key.

Vous pouvez trier s’il y a plus d’éléments que de clés, mais les éléments qui n’ont pas de clés correspondantes ne seront pas triés.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. Vous ne pouvez pas trier s’il y a plus de clés que d’éléments ; Cela lève une ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Le .NET Framework comprend des implémentations prédéfinies de IComparer, présentées dans le tableau suivant.The .NET Framework includes predefined IComparer implementations listed in the following table.

ImplémentationImplementation DescriptionDescription
System.Collections.CaseInsensitiveComparer Compare deux objets quelconques, mais effectue une comparaison de chaînes ne respectant pas la casse.Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default Compare deux objets à l’aide des conventions de tri de la culture actuelle.Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant Compare deux objets à l’aide des conventions de tri de la culture dite indifférente.Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default Compare deux objets de type T à l’aide de l’ordre de tri par défaut du type.Compares two objects of type T by using the type's default sort order.

Vous pouvez également prendre en charge les comparaisons personnalisées en fournissant une instance de votre propre implémentation de IComparer au paramètre comparer.You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. L’exemple fait cela en définissant une implémentation IComparer qui inverse l’ordre de tri par défaut et effectue une comparaison de chaînes ne respectant pas la casse.The example does this by defining an IComparer implementation that reverses the default sort order and performs case-insensitive string comparison.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est le Length de keys.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.

Notes pour les appelants

Le .NET Framework 4 et les versions antérieures utilisaient uniquement l’algorithme tri rapide.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Tri rapide identifie les comparateurs non valides dans certaines situations où l’opération de tri lève une exception IndexOutOfRangeException et lève une exception ArgumentException à l’appelant.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. À partir du .NET Framework 4.5.NET Framework 4.5, il est possible que les opérations de tri qui ont précédemment levé ArgumentException ne lèvent pas d’exception, car les algorithmes de tri et d’insertion HeapSort ne détectent pas un comparateur non valide.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. Pour l’essentiel, cela s’applique aux tableaux avec moins ou égal à 16 éléments.For the most part, this applies to arrays with less than or equal to 16 elements.

Voir aussi

Sort(Array, Array)

Trie une paire d’objets Array unidimensionnels (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’implémentation de IComparable de chaque clé.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)

Paramètres

keys
Array

Array unidimensionnel qui contient les clés à trier.The one-dimensional Array that contains the keys to sort.

items
Array

Array unidimensionnel qui contient les éléments correspondant à chaque clé du keysArray.The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

- ou --or- null pour trier uniquement keysArray.null to sort only the keysArray.

Exceptions

keys a la valeur null.keys is null.

keysArray est multidimensionnel.The keysArray is multidimensional.

- ou --or- itemsArray est multidimensionnel.The itemsArray is multidimensional.

items n’est pas null, et la longueur de keys est supérieure à la longueur d’items.items is not null, and the length of keys is greater than the length of items.

Un ou plusieurs éléments de keysArray n’implémentent pas l’interface IComparable.One or more elements in the keysArray do not implement the IComparable interface.

Exemples

L’exemple suivant montre comment trier deux tableaux associés où le premier tableau contient les clés et le second contient les valeurs.The following example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. Les tris sont effectués à l’aide du comparateur par défaut et d’un comparateur personnalisé qui inverse l’ordre de tri.Sorts are done using the default comparer and a custom comparer that reverses the sort order. Notez que le résultat peut varier en fonction du CultureInfoactuel.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.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub


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

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

   End Sub

End Class


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

Remarques

Chaque clé de la keysArray a un élément correspondant dans leArrayitems.Each key in the keysArray has a corresponding item in the itemsArray. Quand une clé est repositionnée pendant le tri, l’élément correspondant dans la itemsArray est repositionné de manière similaire.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Par conséquent, le itemsArray est trié en fonction de la disposition des clés correspondantes dans leArraykeys.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Chaque clé duArray keysdoit implémenter l’interface IComparable pour pouvoir effectuer des comparaisons avec chaque autre clé.Each key in the keysArray must implement the IComparable interface to be capable of comparisons with every other key.

Vous pouvez trier s’il y a plus d’éléments que de clés, mais les éléments qui n’ont pas de clés correspondantes ne seront pas triés.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. Vous ne pouvez pas trier s’il y a plus de clés que d’éléments ; Cela lève une ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est le Length de keys.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.

Voir aussi

Sort(Array)

Trie les éléments dans l’intégralité d’un Array unidimensionnel à l’aide de l’implémentation IComparable de chaque élément du 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

Paramètres

array
Array

Array unidimensionnel à trier.The one-dimensional Array to sort.

Exceptions

array est null.array is null.

array est multidimensionnel.array is multidimensional.

Un ou plusieurs éléments de array n’implémentent pas l’interface IComparable.One or more elements in array do not implement the IComparable interface.

Exemples

L’exemple de code suivant montre comment trier les valeurs d’un Array à l’aide du comparateur par défaut et d’un comparateur personnalisé qui inverse l’ordre de tri.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. Notez que le résultat peut varier en fonction du CultureInfoactuel.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

Remarques

Chaque élément de array doit implémenter l’interface IComparable afin de pouvoir effectuer des comparaisons avec chaque autre élément dans array.Each element of array must implement the IComparable interface to be capable of comparisons with every other element in array.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est le Length de array.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.

Voir aussi

Sort<T>(T[])

Trie les éléments dans l’intégralité d’un Array à l’aide de l’implémentation de l’interface générique IComparable<T> de chaque élément du 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())

Paramètres de type

T

Type des éléments du tableau.The type of the elements of the array.

Paramètres

array
T[]

Array de base zéro unidimensionnel à trier.The one-dimensional, zero-based Array to sort.

Exceptions

array a la valeur null.array is null.

Un ou plusieurs éléments de array n’implémentent pas l’interface générique IComparable<T>.One or more elements in array do not implement the IComparable<T> generic interface.

Exemples

L’exemple de code suivant illustre la surcharge de méthode générique Sort<T>(T[]) et la surcharge de méthode générique 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. Un tableau de chaînes est créé, sans ordre particulier.An array of strings is created, in no particular order.

Le tableau est affiché, trié et affiché de nouveau.The array is displayed, sorted, and displayed again.

Notes

Les appels aux méthodes génériques Sort et BinarySearch ne sont pas différents des appels à leurs équivalents non génériques, car Visual Basic, C#et C++ déduisent le type du paramètre de type générique à partir du type du premier argument.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. Si vous utilisez Ildasm. exe (Désassembleur il) pour examiner le langage MSIL (Microsoft Intermediate Language), vous pouvez voir que les méthodes génériques sont appelées.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.

La surcharge de méthode générique BinarySearch<T>(T[], T) est ensuite utilisée pour rechercher deux chaînes, une qui ne se trouve pas dans le tableau et une autre qui est.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. Le tableau et la valeur de retour de la méthode BinarySearch sont passés à la méthode générique ShowWhere, qui affiche la valeur d’index si la chaîne est trouvée, et dans le cas contraire, les éléments dont la chaîne de recherche est comprise si elle se trouvait dans le tableau.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. L’index est négatif si la chaîne n’est pas n le tableau, donc la méthode ShowWhere prend le complément de bits (l’opérateur C# ~ dans C++et Visual, Xor -1 dans Visual Basic) pour obtenir l’index du premier élément de la liste qui est plus grand que la chaîne de recherche. exclusive.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.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.

Remarques

Chaque élément de array doit implémenter l’interface générique IComparable<T> pour pouvoir effectuer des comparaisons avec chaque autre élément dans array.Each element of array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est le Length de array.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.

Voir aussi

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

Trie les éléments dans un Array à l’aide de l’interface générique IComparer<T> spécifiée.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))

Paramètres de type

T

Type des éléments du tableau.The type of the elements of the array.

Paramètres

array
T[]

Array de base zéro unidimensionnel à trier.The one-dimensional, zero-base Array to sort

comparer
IComparer<T>

Implémentation de l’interface générique IComparer<T> à utiliser pendant la comparaison d’éléments, ou null pour utiliser l’implémentation de l’interface générique IComparable<T> de chaque élément.The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

Exceptions

array a la valeur null.array is null.

comparer est null, et un ou plusieurs éléments de array n’implémentent pas l’interface générique IComparable<T>.comparer is null, and one or more elements in array do not implement the IComparable<T> generic interface.

L’implémentation de comparer a provoqué une erreur pendant le tri.The implementation of comparer caused an error during the sort. Par exemple, comparer peut ne pas retourner 0 pendant la comparaison d’un élément à lui-même.For example, comparer might not return 0 when comparing an item with itself.

Exemples

L’exemple de code suivant illustre la surcharge de méthode générique Sort<T>(T[], IComparer<T>) et la surcharge de méthode générique 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.

L’exemple de code définit un autre comparateur pour les chaînes, nommé ReverseCompare, qui implémente l’interface générique IComparer<string> (IComparer(Of String) dans Visual Basic, C++IComparer<String^> en visuel).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. Le comparateur appelle la méthode CompareTo(String), en inversant l’ordre des comparateurs afin que les chaînes soient triées de haut en bas et non de bas en haut.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.

Le tableau est affiché, trié et affiché de nouveau.The array is displayed, sorted, and displayed again. Les tableaux doivent être triés pour pouvoir utiliser la méthode BinarySearch.Arrays must be sorted in order to use the BinarySearch method.

Notes

Les appels aux méthodes génériques Sort<T>(T[], IComparer<T>) et BinarySearch<T>(T[], T, IComparer<T>) ne sont pas différents des appels à leurs équivalents non génériques, car Visual Basic, C#et C++ déduisent le type du paramètre de type générique à partir du type du premier argument.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. Si vous utilisez Ildasm. exe (Désassembleur il) pour examiner le langage MSIL (Microsoft Intermediate Language), vous pouvez voir que les méthodes génériques sont appelées.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.

La surcharge de méthode générique BinarySearch<T>(T[], T, IComparer<T>) est ensuite utilisée pour rechercher deux chaînes, une qui ne se trouve pas dans le tableau et une autre qui est.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. Le tableau et la valeur de retour de la méthode BinarySearch<T>(T[], T, IComparer<T>) sont passés à la méthode générique ShowWhere, qui affiche la valeur d’index si la chaîne est trouvée, et dans le cas contraire, les éléments dont la chaîne de recherche est comprise si elle se trouvait dans le tableau.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. L’index est négatif si la chaîne n’est pas n le tableau, donc la méthode ShowWhere prend le complément de bits (l’opérateur C# ~ dans C++et Visual, Xor -1 dans Visual Basic) pour obtenir l’index du premier élément de la liste qui est plus grand que la chaîne de recherche. exclusive.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.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.

Remarques

Si comparer est null, chaque élément de array doit implémenter l’interface générique IComparable<T> pour pouvoir effectuer des comparaisons avec chaque autre élément dans 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.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est le Length de array.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.

Notes pour les appelants

Le .NET Framework 4 et les versions antérieures utilisaient uniquement l’algorithme tri rapide.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Tri rapide identifie les comparateurs non valides dans certaines situations où l’opération de tri lève une exception IndexOutOfRangeException et lève une exception ArgumentException à l’appelant.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. À partir du .NET Framework 4.5.NET Framework 4.5, il est possible que les opérations de tri qui ont précédemment levé ArgumentException ne lèvent pas d’exception, car les algorithmes de tri et d’insertion HeapSort ne détectent pas un comparateur non valide.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. Pour l’essentiel, cela s’applique aux tableaux avec moins ou égal à 16 éléments.For the most part, this applies to arrays with less than or equal to 16 elements.

Voir aussi

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

Trie les éléments inclus dans un Array à l’aide de l’objet Comparison<T> spécifié.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))

Paramètres de type

T

Type des éléments du tableau.The type of the elements of the array.

Paramètres

array
T[]

Array de base zéro unidimensionnel à trier.The one-dimensional, zero-based Array to sort

comparison
Comparison<T>

Comparison<T> à utiliser pendant la comparaison d'éléments.The Comparison<T> to use when comparing elements.

Exceptions

array est null.array is null.

- ou --or- comparison a la valeur null.comparison is null.

L’implémentation de comparison a provoqué une erreur pendant le tri.The implementation of comparison caused an error during the sort. Par exemple, comparison peut ne pas retourner 0 pendant la comparaison d’un élément à lui-même.For example, comparison might not return 0 when comparing an item with itself.

Exemples

L’exemple de code suivant illustre la surcharge de méthode Sort(Comparison<T>).The following code example demonstrates the Sort(Comparison<T>) method overload.

L’exemple de code définit une autre méthode de comparaison pour les chaînes, nommée CompareDinosByLength.The code example defines an alternative comparison method for strings, named CompareDinosByLength. Cette méthode fonctionne comme suit : Tout d’abord, les comparateurs sont testés pournull, et une référence null est traitée comme inférieure à une valeur non null.This method works as follows: First, the comparands are tested fornull, and a null reference is treated as less than a non-null. Deuxièmement, les longueurs de chaîne sont comparées et la chaîne la plus longue est considérée comme supérieure.Second, the string lengths are compared, and the longer string is deemed to be greater. Troisièmement, si les longueurs sont égales, la comparaison de chaînes ordinaire est utilisée.Third, if the lengths are equal, ordinary string comparison is used.

Un tableau de chaînes est créé et rempli avec quatre chaînes, dans aucun ordre particulier.A array of strings is created and populated with four strings, in no particular order. La liste comprend également une chaîne vide et une référence null.The list also includes an empty string and a null reference. La liste s’affiche, triée à l’aide d’un délégué générique Comparison<T> représentant la méthode CompareDinosByLength, puis affichée à nouveau.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.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"

Remarques

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort (in) comme suit :This method uses introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est le Length de array.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.

Notes pour les appelants

Le .NET Framework 4 et les versions antérieures utilisaient uniquement l’algorithme tri rapide.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Tri rapide identifie les comparateurs non valides dans certaines situations où l’opération de tri lève une exception IndexOutOfRangeException et lève une exception ArgumentException à l’appelant.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. À partir du .NET Framework 4.5.NET Framework 4.5, il est possible que les opérations de tri qui ont précédemment levé ArgumentException ne lèvent pas d’exception, car les algorithmes de tri et d’insertion HeapSort ne détectent pas un comparateur non valide.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. Pour l’essentiel, cela s’applique aux tableaux avec moins de 6 éléments.For the most part, this applies to arrays with less than or equal to 6 elements.

Voir aussi

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

Trie les éléments d’une plage d’éléments d’un Array à l’aide de l’implémentation de l’interface générique IComparable<T> de chaque élément de 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)

Paramètres de type

T

Type des éléments du tableau.The type of the elements of the array.

Paramètres

array
T[]

Array de base zéro unidimensionnel à trier.The one-dimensional, zero-based Array to sort

index
Int32

Index de départ de la plage à trier.The starting index of the range to sort.

length
Int32

Nombre d'éléments à trier dans la plage.The number of elements in the range to sort.

Exceptions

array a la valeur null.array is null.

index est inférieur à la limite inférieure de array.index is less than the lower bound of array.

- ou --or- length est inférieur à zéro.length is less than zero.

index et length ne spécifient pas une plage valide dans array.index and length do not specify a valid range in array.

Un ou plusieurs éléments de array n’implémentent pas l’interface générique IComparable<T>.One or more elements in array do not implement the IComparable<T> generic interface.

Exemples

L’exemple de code suivant illustre la surcharge de méthode générique Sort<T>(T[], Int32, Int32) et la surcharge de méthode générique Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) pour trier une plage dans un tableau.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.

L’exemple de code définit un autre comparateur pour les chaînes, nommé ReverseCompare, qui implémente l’interface générique IComparer<string> (IComparer(Of String) dans Visual Basic, C++IComparer<String^> en visuel).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. Le comparateur appelle la méthode CompareTo(String), en inversant l’ordre des comparateurs afin que les chaînes soient triées de haut en bas et non de bas en haut.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.

L’exemple de code crée et affiche un tableau de noms de dinosaures, constitué de trois herbivores suivis de trois carnivores (tyrannosaurids, pour être précis).The code example creates and displays an array of dinosaur names, consisting of three herbivores followed by three carnivores (tyrannosaurids, to be precise). La surcharge de méthode générique Sort<T>(T[], Int32, Int32) est utilisée pour trier les trois derniers éléments du tableau, qui est ensuite affiché.The Sort<T>(T[], Int32, Int32) generic method overload is used to sort the last three elements of the array, which is then displayed. La surcharge de méthode générique Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) est utilisée avec ReverseCompare pour trier les trois derniers éléments dans l’ordre inverse.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. Les dinosaures entièrement déconcertées s’affichent à nouveau.The thoroughly confused dinosaurs are displayed again.

Notes

Les appels aux méthodes génériques Sort<T>(T[], IComparer<T>) et BinarySearch<T>(T[], T, IComparer<T>) ne sont pas différents des appels à leurs équivalents non génériques, car Visual Basic, C#et C++ déduisent le type du paramètre de type générique à partir du type du premier argument.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. Si vous utilisez Ildasm. exe (Désassembleur il) pour examiner le langage MSIL (Microsoft Intermediate Language), vous pouvez voir que les méthodes génériques sont appelées.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.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

Remarques

Chaque élément dans la plage d’éléments spécifiée de array doit implémenter l’interface générique IComparable<T> afin de pouvoir effectuer des comparaisons avec chaque autre élément dans 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.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est length.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.

Voir aussi

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

Trie les éléments d’une plage d’éléments dans un Array à l’aide de l’interface générique IComparer<T> spécifiée.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))

Paramètres de type

T

Type des éléments du tableau.The type of the elements of the array.

Paramètres

array
T[]

Array de base zéro unidimensionnel à trier.The one-dimensional, zero-based Array to sort.

index
Int32

Index de départ de la plage à trier.The starting index of the range to sort.

length
Int32

Nombre d'éléments à trier dans la plage.The number of elements in the range to sort.

comparer
IComparer<T>

Implémentation de l'interface générique IComparer<T> à utiliser lors de la comparaison d'éléments, ou null pour utiliser l'implémentation de l'interface générique IComparable<T> de chaque élément.The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

Exceptions

array a la valeur null.array is null.

index est inférieur à la limite inférieure de array.index is less than the lower bound of array.

- ou --or- length est inférieur à zéro.length is less than zero.

index et length ne spécifient pas une plage valide dans array.index and length do not specify a valid range in array.

- ou --or- L’implémentation de comparer a provoqué une erreur pendant le tri.The implementation of comparer caused an error during the sort. Par exemple, comparer peut ne pas retourner 0 pendant la comparaison d’un élément à lui-même.For example, comparer might not return 0 when comparing an item with itself.

comparer est null, et un ou plusieurs éléments de array n’implémentent pas l’interface générique IComparable<T>.comparer is null, and one or more elements in array do not implement the IComparable<T> generic interface.

Exemples

L’exemple de code suivant illustre la surcharge de méthode générique Sort<T>(T[], Int32, Int32) et la surcharge de méthode générique Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) pour trier une plage dans un tableau.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.

L’exemple de code définit un autre comparateur pour les chaînes, nommé ReverseCompare, qui implémente l’interface générique IComparer<string> (IComparer(Of String) dans Visual Basic, C++IComparer<String^> en visuel).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. Le comparateur appelle la méthode CompareTo(String), en inversant l’ordre des comparateurs afin que les chaînes soient triées de haut en bas et non de bas en haut.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.

L’exemple de code crée et affiche un tableau de noms de dinosaures, constitué de trois herbivores suivis de trois carnivores (tyrannosaurids, pour être précis).The code example creates and displays an array of dinosaur names, consisting of three herbivores followed by three carnivores (tyrannosaurids, to be precise). La surcharge de méthode générique Sort<T>(T[], Int32, Int32) est utilisée pour trier les trois derniers éléments du tableau, qui est ensuite affiché.The Sort<T>(T[], Int32, Int32) generic method overload is used to sort the last three elements of the array, which is then displayed. La surcharge de méthode générique Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) est utilisée avec ReverseCompare pour trier les trois derniers éléments dans l’ordre inverse.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. Les dinosaures entièrement déconcertées s’affichent à nouveau.The thoroughly confused dinosaurs are displayed again.

Notes

Les appels aux méthodes génériques Sort<T>(T[], IComparer<T>) et BinarySearch<T>(T[], T, IComparer<T>) ne sont pas différents des appels à leurs équivalents non génériques, car Visual Basic, C#et C++ déduisent le type du paramètre de type générique à partir du type du premier argument.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. Si vous utilisez Ildasm. exe (Désassembleur il) pour examiner le langage MSIL (Microsoft Intermediate Language), vous pouvez voir que les méthodes génériques sont appelées.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.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

Remarques

Si comparer est null, chaque élément de la plage spécifiée d’éléments dans array doit implémenter l’interface générique IComparable<T> pour pouvoir effectuer des comparaisons avec chaque autre élément dans 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.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est length.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.

Notes pour les appelants

Le .NET Framework 4 et les versions antérieures utilisaient uniquement l’algorithme tri rapide.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Tri rapide identifie les comparateurs non valides dans certaines situations où l’opération de tri lève une exception IndexOutOfRangeException et lève une exception ArgumentException à l’appelant.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. À partir du .NET Framework 4.5.NET Framework 4.5, il est possible que les opérations de tri qui ont précédemment levé ArgumentException ne lèvent pas d’exception, car les algorithmes de tri et d’insertion HeapSort ne détectent pas un comparateur non valide.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. Pour l’essentiel, cela s’applique aux tableaux avec moins ou égal à 16 éléments.For the most part, this applies to arrays with less than or equal to 16 elements.

Voir aussi

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

Trie une paire d’objets Array (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’implémentation de l’interface générique IComparable<T> de chaque clé.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())

Paramètres de type

TKey

Type des éléments du tableau des clés.The type of the elements of the key array.

TValue

Type des éléments du tableau des éléments.The type of the elements of the items array.

Paramètres

keys
TKey[]

Array unidimensionnel de base zéro qui contient les clés à trier.The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

Array unidimensionnel de base zéro qui contient les éléments correspondant aux clés dans keys, ou null pour trier uniquement keys.The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

Exceptions

keys a la valeur null.keys is null.

items n’est pas null, et la limite inférieure de keys ne correspond pas à la limite inférieure de items.items is not null, and the lower bound of keys does not match the lower bound of items.

- ou --or- items n’est pas null, et la longueur de keys est supérieure à la longueur d’items.items is not null, and the length of keys is greater than the length of items.

Un ou plusieurs éléments de keysArray n’implémentent pas l’interface générique IComparable<T>.One or more elements in the keysArray do not implement the IComparable<T> generic interface.

Exemples

L’exemple de code suivant montre les surcharges de méthode générique Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) et Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>), pour trier des paires de tableaux qui représentent des clés et des valeurs.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.

L’exemple de code définit un autre comparateur pour les chaînes, nommé ReverseCompare, qui implémente l’interface générique IComparer<string> (IComparer(Of String) dans Visual Basic, C++IComparer<String^> en visuel).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. Le comparateur appelle la méthode CompareTo(String), en inversant l’ordre des comparateurs afin que les chaînes soient triées de haut en bas et non de bas en haut.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.

L’exemple de code crée et affiche un tableau de noms de dinosaures (les clés) et un tableau d’entiers représentant la longueur maximale de chaque dinosaure en mètres (valeurs).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). Les tableaux sont ensuite triés et affichés plusieurs fois :The arrays are then sorted and displayed several times:

Notes

Les appels aux méthodes génériques ne sont pas différents des appels à leurs équivalents non génériques, car Visual Basic, C#et C++ déduisent le type du paramètre de type générique à partir du type des deux premiers arguments.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. Si vous utilisez Ildasm. exe (Désassembleur il) pour examiner le langage MSIL (Microsoft Intermediate Language), vous pouvez voir que les méthodes génériques sont appelées.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.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.

Remarques

Chaque clé de la keysArray a un élément correspondant dans leArrayitems.Each key in the keysArray has a corresponding item in the itemsArray. Quand une clé est repositionnée pendant le tri, l’élément correspondant dans la itemsArray est repositionné de manière similaire.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Par conséquent, le itemsArray est trié en fonction de la disposition des clés correspondantes dans leArraykeys.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Chaque clé duArray keysdoit implémenter l’interface générique IComparable<T> pour pouvoir effectuer des comparaisons avec chaque autre clé.Each key in the keysArray must implement the IComparable<T> generic interface to be capable of comparisons with every other key.

Vous pouvez trier s’il y a plus d’éléments que de clés, mais les éléments qui n’ont pas de clés correspondantes ne seront pas triés.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. Vous ne pouvez pas trier s’il y a plus de clés que d’éléments ; Cela lève une ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est le Length de array.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.

Voir aussi

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

Trie une paire d’objets Array (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’interface générique IComparer<T> spécifiée.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))

Paramètres de type

TKey

Type des éléments du tableau des clés.The type of the elements of the key array.

TValue

Type des éléments du tableau des éléments.The type of the elements of the items array.

Paramètres

keys
TKey[]

Array unidimensionnel de base zéro qui contient les clés à trier.The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

Array unidimensionnel de base zéro qui contient les éléments qui correspondent aux clés dans keys, ou null pour trier uniquement keys.The 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>

Implémentation de l’interface générique IComparer<T> à utiliser pendant la comparaison d’éléments, ou null pour utiliser l’implémentation de l’interface générique IComparable<T> de chaque élément.The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

Exceptions

keys a la valeur null.keys is null.

items n’est pas null, et la limite inférieure de keys ne correspond pas à la limite inférieure de items.items is not null, and the lower bound of keys does not match the lower bound of items.

- ou --or- items n’est pas null, et la longueur de keys est supérieure à la longueur d’items.items is not null, and the length of keys is greater than the length of items.

- ou --or- L’implémentation de comparer a provoqué une erreur pendant le tri.The implementation of comparer caused an error during the sort. Par exemple, comparer peut ne pas retourner 0 pendant la comparaison d’un élément à lui-même.For example, comparer might not return 0 when comparing an item with itself.

comparer est null, et un ou plusieurs éléments de keysArray n’implémentent pas l’interface générique IComparable<T>.comparer is null, and one or more elements in the keysArray do not implement the IComparable<T> generic interface.

Exemples

L’exemple de code suivant illustre l' 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 %7 %600% 7D %29 >,Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)et Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Generic surcharges de méthode, pour trier des paires de tableaux qui représentent des clés et des valeurs.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.

L’exemple de code définit un autre comparateur pour les chaînes, nommé ReverseCompare, qui implémente l’interface générique IComparer<string> (IComparer(Of String) dans Visual Basic, C++IComparer<String^> en visuel).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. Le comparateur appelle la méthode CompareTo(String), en inversant l’ordre des comparateurs afin que les chaînes soient triées de haut en bas et non de bas en haut.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.

L’exemple de code crée et affiche un tableau de noms de dinosaures (les clés) et un tableau d’entiers représentant la longueur maximale de chaque dinosaure en mètres (valeurs).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). Les tableaux sont ensuite triés et affichés plusieurs fois :The arrays are then sorted and displayed several times:

Notes

Les appels aux méthodes génériques ne sont pas différents des appels à leurs équivalents non génériques, car Visual Basic, C#et C++ déduisent le type du paramètre de type générique à partir du type des deux premiers arguments.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. Si vous utilisez Ildasm. exe (Désassembleur il) pour examiner le langage MSIL (Microsoft Intermediate Language), vous pouvez voir que les méthodes génériques sont appelées.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.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.

Remarques

Chaque clé de la keysArray a un élément correspondant dans leArrayitems.Each key in the keysArray has a corresponding item in the itemsArray. Quand une clé est repositionnée pendant le tri, l’élément correspondant dans la itemsArray est repositionné de manière similaire.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Par conséquent, le itemsArray est trié en fonction de la disposition des clés correspondantes dans leArraykeys.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Si comparer est null, chaque clé de laArray keysdoit implémenter l’interface générique IComparable<T> pour pouvoir faire des comparaisons avec chaque autre clé.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.

Vous pouvez trier s’il y a plus d’éléments que de clés, mais les éléments qui n’ont pas de clés correspondantes ne seront pas triés.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. Vous ne pouvez pas trier s’il y a plus de clés que d’éléments ; Cela lève une ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est le Length de array.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.

Notes pour les appelants

Le .NET Framework 4 et les versions antérieures utilisaient uniquement l’algorithme tri rapide.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Tri rapide identifie les comparateurs non valides dans certaines situations où l’opération de tri lève une exception IndexOutOfRangeException et lève une exception ArgumentException à l’appelant.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. À partir du .NET Framework 4.5.NET Framework 4.5, il est possible que les opérations de tri qui ont précédemment levé ArgumentException ne lèvent pas d’exception, car les algorithmes de tri et d’insertion HeapSort ne détectent pas un comparateur non valide.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. Pour l’essentiel, cela s’applique aux tableaux avec moins ou égal à 16 éléments.For the most part, this applies to arrays with less than or equal to 16 elements.

Voir aussi

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

Trie une plage d’éléments dans une paire d’objets Array (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’implémentation d’interface générique IComparable<T> de chaque clé.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)

Paramètres de type

TKey

Type des éléments du tableau des clés.The type of the elements of the key array.

TValue

Type des éléments du tableau des éléments.The type of the elements of the items array.

Paramètres

keys
TKey[]

Array unidimensionnel de base zéro qui contient les clés à trier.The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

Array unidimensionnel de base zéro qui contient les éléments correspondant aux clés dans keys, ou null pour trier uniquement keys.The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

index
Int32

Index de départ de la plage à trier.The starting index of the range to sort.

length
Int32

Nombre d'éléments à trier dans la plage.The number of elements in the range to sort.

Exceptions

keys a la valeur null.keys is null.

index est inférieur à la limite inférieure de keys.index is less than the lower bound of keys.

- ou --or- length est inférieur à zéro.length is less than zero.

items n’est pas null, et la limite inférieure de keys ne correspond pas à la limite inférieure de items.items is not null, and the lower bound of keys does not match the lower bound of items.

- ou --or- items n’est pas null, et la longueur de keys est supérieure à la longueur d’items.items is not null, and the length of keys is greater than the length of items.

- ou --or- index et length ne spécifient pas une plage valide dans keysArray.index and length do not specify a valid range in the keysArray.

- ou --or- items n’est pas null, et index et length ne spécifient pas une plage valide dans itemsArray.items is not null, and index and length do not specify a valid range in the itemsArray.

Un ou plusieurs éléments de keysArray n’implémentent pas l’interface générique IComparable<T>.One or more elements in the keysArray do not implement the IComparable<T> generic interface.

Exemples

L’exemple de code suivant montre les Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), [], TValue<XREF : System. Array. sort %60 %602 %28% 2CSystem. Int32% 2CSystem. Int32% 1 >, et Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) des surcharges de méthode générique, par exemple, pour les éléments suivants : Tri des paires de tableaux qui représentent des clés et des valeurs.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.

L’exemple de code définit un autre comparateur pour les chaînes, nommé ReverseCompare, qui implémente l’interface générique IComparer<string> (IComparer(Of String) dans Visual Basic, C++IComparer<String^> en visuel).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. Le comparateur appelle la méthode CompareTo(String), en inversant l’ordre des comparateurs afin que les chaînes soient triées de haut en bas et non de bas en haut.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.

L’exemple de code crée et affiche un tableau de noms de dinosaures (les clés) et un tableau d’entiers représentant la longueur maximale de chaque dinosaure en mètres (valeurs).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). Les tableaux sont ensuite triés et affichés plusieurs fois :The arrays are then sorted and displayed several times:

Notes

Les appels aux méthodes génériques ne sont pas différents des appels à leurs équivalents non génériques, car Visual Basic, C#et C++ déduisent le type du paramètre de type générique à partir du type des deux premiers arguments.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. Si vous utilisez Ildasm. exe (Désassembleur il) pour examiner le langage MSIL (Microsoft Intermediate Language), vous pouvez voir que les méthodes génériques sont appelées.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.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.

Remarques

Chaque clé de la keysArray a un élément correspondant dans leArrayitems.Each key in the keysArray has a corresponding item in the itemsArray. Quand une clé est repositionnée pendant le tri, l’élément correspondant dans la itemsArray est repositionné de manière similaire.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Par conséquent, le itemsArray est trié en fonction de la disposition des clés correspondantes dans leArraykeys.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Chaque clé dans la plage spécifiée d’éléments dans leArray keysdoit implémenter l’interface générique IComparable<T> pour pouvoir effectuer des comparaisons avec chaque autre clé.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.

Vous pouvez trier s’il y a plus d’éléments que de clés, mais les éléments qui n’ont pas de clés correspondantes ne seront pas triés.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. Vous ne pouvez pas trier s’il y a plus de clés que d’éléments ; Cela lève une ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est length.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.

Voir aussi

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

Trie une plage d’éléments dans une paire d’objets Array (l’un contient les clés et l’autre, les éléments correspondants) en fonction des clés du premier Array à l’aide de l’interface générique IComparer<T> spécifiée.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))

Paramètres de type

TKey

Type des éléments du tableau des clés.The type of the elements of the key array.

TValue

Type des éléments du tableau des éléments.The type of the elements of the items array.

Paramètres

keys
TKey[]

Array unidimensionnel de base zéro qui contient les clés à trier.The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

Array unidimensionnel de base zéro qui contient les éléments correspondant aux clés dans keys, ou null pour trier uniquement keys.The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

index
Int32

Index de départ de la plage à trier.The starting index of the range to sort.

length
Int32

Nombre d'éléments à trier dans la plage.The number of elements in the range to sort.

comparer
IComparer<TKey>

Implémentation de l’interface générique IComparer<T> à utiliser pendant la comparaison d’éléments, ou null pour utiliser l’implémentation de l’interface générique IComparable<T> de chaque élément.The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

Exceptions

keys a la valeur null.keys is null.

index est inférieur à la limite inférieure de keys.index is less than the lower bound of keys.

- ou --or- length est inférieur à zéro.length is less than zero.

items n’est pas null, et la limite inférieure de keys ne correspond pas à la limite inférieure de items.items is not null, and the lower bound of keys does not match the lower bound of items.

- ou --or- items n’est pas null, et la longueur de keys est supérieure à la longueur d’items.items is not null, and the length of keys is greater than the length of items.

- ou --or- index et length ne spécifient pas une plage valide dans keysArray.index and length do not specify a valid range in the keysArray.

- ou --or- items n’est pas null, et index et length ne spécifient pas une plage valide dans itemsArray.items is not null, and index and length do not specify a valid range in the itemsArray.

- ou --or- L’implémentation de comparer a provoqué une erreur pendant le tri.The implementation of comparer caused an error during the sort. Par exemple, comparer peut ne pas retourner 0 pendant la comparaison d’un élément à lui-même.For example, comparer might not return 0 when comparing an item with itself.

comparer est null, et un ou plusieurs éléments de keysArray n’implémentent pas l’interface générique IComparable<T>.comparer is null, and one or more elements in the keysArray do not implement the IComparable<T> generic interface.

Exemples

L’exemple de code suivant montre les Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)et [], 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 > surcharges de méthode générique, pour trier des paires de tableaux qui représentent des clés et des valeurs.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.

L’exemple de code définit un autre comparateur pour les chaînes, nommé ReverseCompare, qui implémente l’interface générique IComparer<string> (IComparer(Of String) dans Visual Basic, C++IComparer<String^> en visuel).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. Le comparateur appelle la méthode CompareTo(String), en inversant l’ordre des comparateurs afin que les chaînes soient triées de haut en bas et non de bas en haut.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.

L’exemple de code crée et affiche un tableau de noms de dinosaures (les clés) et un tableau d’entiers représentant la longueur maximale de chaque dinosaure en mètres (valeurs).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). Les tableaux sont ensuite triés et affichés plusieurs fois :The arrays are then sorted and displayed several times:

  • La surcharge Sort<TKey,TValue>(TKey[], TValue[]) est utilisée pour trier les deux tableaux dans l’ordre des noms de dinosaures dans le premier tableau.The Sort<TKey,TValue>(TKey[], TValue[]) overload is used to sort both arrays in order of the dinosaur names in the first array.

  • La surcharge Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) et une instance de ReverseCompare sont utilisées pour inverser l’ordre de tri des tableaux associés.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.

  • La surcharge Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) est utilisée pour trier les trois derniers éléments des deux tableaux.The Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) overload is used to sort the last three elements of both arrays.

  • La surcharge [], TValue<XREF : System. Array. sort %60 %602 %28 %60 %600% 5B% n% 2CSystem. Int32%, %1, 1, 2CSystem. Int32% 2CSystem. Collections. Generic. IComparer% 7B %60 %600% 7D %29 > est utilisée pour trier les trois derniers éléments des deux tableaux dans l’ordre inverse.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.

Notes

Les appels aux méthodes génériques ne sont pas différents des appels à leurs équivalents non génériques, car Visual Basic, C#et C++ déduisent le type du paramètre de type générique à partir du type des deux premiers arguments.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. Si vous utilisez Ildasm. exe (Désassembleur il) pour examiner le langage MSIL (Microsoft Intermediate Language), vous pouvez voir que les méthodes génériques sont appelées.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.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.

Remarques

Chaque clé de la keysArray a un élément correspondant dans leArrayitems.Each key in the keysArray has a corresponding item in the itemsArray. Quand une clé est repositionnée pendant le tri, l’élément correspondant dans la itemsArray est repositionné de manière similaire.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Par conséquent, le itemsArray est trié en fonction de la disposition des clés correspondantes dans leArraykeys.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Si comparer est null, chaque clé de la plage spécifiée d’éléments dans leArray de keysdoit implémenter l’interface générique IComparable<T> pour pouvoir effectuer des comparaisons avec chaque autre clé.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.

Vous pouvez trier s’il y a plus d’éléments que de clés, mais les éléments qui n’ont pas de clés correspondantes ne seront pas triés.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. Vous ne pouvez pas trier s’il y a plus de clés que d’éléments ; Cela lève une ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si le tri n’aboutit pas, les résultats ne sont pas définis.If the sort is not successfully completed, the results are undefined.

Cette méthode utilise l’algorithme de tri Introsort, comme suit :This method uses the introspective sort (introsort) algorithm as follows:

  • Si la taille de la partition est inférieure ou égale à 16 éléments, elle utilise un algorithme de tri d’insertion .If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm.

  • Si le nombre de partitions dépasse 2 * logN, où n est la plage du tableau d’entrée, il utilise un algorithme HeapSort .If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • Dans le cas contraire, il utilise un algorithme tri rapide .Otherwise, it uses a Quicksort algorithm.

Cette implémentation effectue un tri instable ; autrement dit, si deux éléments sont égaux, leur ordre peut ne pas être préservé.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En revanche, un tri stable préserve l’ordre des éléments qui sont égaux.In contrast, a stable sort preserves the order of elements that are equal.

Pour les tableaux triés à l’aide des algorithmes HeapSort et tri rapide, dans le pire des cas, cette méthode est une opération O (n log n), où n est length.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.

Notes pour les appelants

Le .NET Framework 4 et les versions antérieures utilisaient uniquement l’algorithme tri rapide.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. Tri rapide identifie les comparateurs non valides dans certaines situations où l’opération de tri lève une exception IndexOutOfRangeException et lève une exception ArgumentException à l’appelant.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. À partir du .NET Framework 4.5.NET Framework 4.5, il est possible que les opérations de tri qui ont précédemment levé ArgumentException ne lèvent pas d’exception, car les algorithmes de tri et d’insertion HeapSort ne détectent pas un comparateur non valide.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. Pour l’essentiel, cela s’applique aux tableaux avec moins ou égal à 16 éléments.For the most part, this applies to arrays with less than or equal to 16 elements.

Voir aussi

S’applique à