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

Definición

Ordena los elementos en una matriz unidimensional.Sorts the elements in a one-dimensional array.

Sobrecargas

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

Ordena los elementos de un intervalo de elementos de unidimensional Array usando la interfaz IComparer.Sorts the elements in a range of elements in a one-dimensional Array using the specified IComparer.

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

Ordena un intervalo de elementos de un par de objetos Array unidimensionales (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera Array usando la interfaz IComparer especificada.Sorts a range of elements in a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer.

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

Ordena los elementos de un intervalo de elementos de una matriz Array unidimensional mediante el uso de la implementación de IComparable de cada elemento de la matriz Array.Sorts the elements in a range of elements in a one-dimensional Array using the IComparable implementation of each element of the Array.

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

Ordena un intervalo de elementos en un par de objetos Array unidimensionales (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera matriz Array usando la implementación de IComparable de cada clave.Sorts a range of elements in a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

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

Ordena los elementos de una matriz Array unidimensional usando la interfaz IComparer especificada.Sorts the elements in a one-dimensional Array using the specified IComparer.

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

Ordena un par de objetos Array unidimensionales (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera Array usando la IComparer. especificada.Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer.

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

Ordena un par de objetos Array unidimensionales (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera Array usando la implementación de IComparable de cada clave.Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

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

Ordena los elementos de toda una matriz Array unidimensional usando la implementación de IComparable de cada elemento de la matriz Array.Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.

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

Ordena los elementos de toda una matriz Array usando la implementación de la interfaz genérica IComparable<T> de cada elemento de Array.Sorts the elements in an entire Array using the IComparable<T> generic interface implementation of each element of the Array.

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

Ordena los elementos de una Array usando la interfaz genérica IComparer<T> especificada.Sorts the elements in an Array using the specified IComparer<T> generic interface.

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

Ordena los elementos de una Array usando el Comparison<T> especificado.Sorts the elements in an Array using the specified Comparison<T>.

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

Ordena los elementos en un intervalo de elementos en una Array mediante la implementación de interfaz genérica IComparable<T> de cada elemento de la Array.Sorts the elements in a range of elements in an Array using the IComparable<T> generic interface implementation of each element of the Array.

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

Ordena los elementos de un intervalo de elementos en un elemento Array mediante la interfaz genérica IComparer<T> especificada.Sorts the elements in a range of elements in an Array using the specified IComparer<T> generic interface.

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

Ordena un par de objetos Array (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera Array usando la implementación de la interfaz genérica IComparable<T> de cada clave.Sorts a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable<T> generic interface implementation of each key.

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

Ordena un par de objetos Array (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera matriz Array usando la interfaz genérica IComparer<T> especificada.Sorts a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer<T> generic interface.

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

Ordena un intervalo de elementos en un par de objetos Array (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera matriz Array usando la implementación de la interfaz genérica IComparable<T> de cada clave.Sorts a range of elements in a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable<T> generic interface implementation of each key.

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

Ordena un intervalo de elementos de un par de objetos Array (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera matriz Array usando la interfaz genérica IComparer<T> especificada.Sorts a range of elements in a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer<T> generic interface.

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

Ordena los elementos de un intervalo de elementos de unidimensional Array usando la interfaz IComparer.Sorts the elements in a range of elements in a one-dimensional Array using the specified IComparer.

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

Parámetros

array
Array Array Array Array

Array unidimensional que se va a ordenar.The one-dimensional Array to sort.

index
Int32 Int32 Int32 Int32

Índice inicial del intervalo que se va a ordenar.The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

Número de elementos del intervalo que se va a ordenar.The number of elements in the range to sort.

comparer
IComparer IComparer IComparer IComparer

Implementación de IComparer que se va a usar al comparar elementos.The IComparer implementation to use when comparing elements.

-o bien--or- null para usar la implementación de IComparable de cada elemento.null to use the IComparable implementation of each element.

Excepciones

array es multidimensional.array is multidimensional.

index es menor que el límite inferior de array.index is less than the lower bound of array.

-o bien--or- length es menor que cero.length is less than zero.

index y length no especifican un intervalo válido en array.index and length do not specify a valid range in array.

-o bien--or- La implementación de comparer produjo un error durante la ordenación.The implementation of comparer caused an error during the sort. Por ejemplo, es posible que comparer no devuelva 0 al comparar un elemento consigo mismo.For example, comparer might not return 0 when comparing an item with itself.

comparer es null y uno o más elementos de la array no implementan la interfaz de IComparable.comparer is null, and one or more elements in array do not implement the IComparable interface.

Ejemplos

El ejemplo de código siguiente muestra cómo ordenar los valores de un Array utilizando el comparador predeterminado y un comparador personalizado que invierte el criterio de ordenación.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. Tenga en cuenta que el resultado puede variar según la actual CultureInfo.Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

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

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

   Console::WriteLine();
}

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

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

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

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

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

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

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

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

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

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

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

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

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

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

Comentarios

Si comparer es null, cada elemento dentro del intervalo especificado de elementos de array debe implementar la IComparable para realizar comparaciones con todos los elementos de interfaz de 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 el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

.NET Framework incluye predefinidos IComparer implementaciones se muestran en la tabla siguiente.The .NET Framework includes predefined IComparer implementations listed in the following table.

ImplementaciónImplementation DescripciónDescription
System.Collections.CaseInsensitiveComparer Compara los dos objetos, pero se realiza una comparación entre mayúsculas y minúsculas de cadenas.Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default Compara los dos objetos usando las convenciones de ordenación de la referencia cultural actual.Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant Compara los dos objetos usando las convenciones de ordenación de la referencia cultural invariable.Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default Compara dos objetos de tipo T utilizando el criterio de ordenación predeterminado del tipo.Compares two objects of type T by using the type's default sort order.

También puede admitir las comparaciones personalizadas, ya que proporciona una instancia de su propio IComparer implementación para el comparer parámetro.You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. El ejemplo hace esto mediante la definición de un ReverseComparer clase que se invierte el criterio de ordenación predeterminado para las instancias de un tipo y realiza la comparación de cadenas entre mayúsculas y minúsculas.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.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es 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.

Notas a los autores de las llamadas

El .NET Framework 4 y versiones anteriores usan solo el algoritmo Quicksort.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. QuickSort identifica comparadores no válidos en algunas situaciones en que se inicia la operación de ordenación una IndexOutOfRangeException excepción e inicia un ArgumentException excepción al llamador.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. A partir de la .NET Framework 4.5.NET Framework 4.5, es posible que las operaciones de ordenación que anteriormente produjo ArgumentException no se iniciará una excepción, ya que los algoritmos de ordenación y heapsort de inserción no detectan un comparador no válido.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. En su mayor parte, esto se aplica a las matrices con menos de 16 elementos.For the most part, this applies to arrays with fewer than 16 elements.

Consulte también:

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

Ordena un intervalo de elementos de un par de objetos Array unidimensionales (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera Array usando la interfaz IComparer especificada.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)

Parámetros

keys
Array Array Array Array

La Array unidimensional que contiene las claves que se van a ordenar.The one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

Array unidimensional que contiene los elementos que corresponden a cada una de las claves del objeto keysArray.The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

-o bien--or- null para ordenar solo el objeto keysArray.null to sort only the keysArray.

index
Int32 Int32 Int32 Int32

Índice inicial del intervalo que se va a ordenar.The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

Número de elementos del intervalo que se va a ordenar.The number of elements in the range to sort.

comparer
IComparer IComparer IComparer IComparer

Implementación de IComparer que se va a usar al comparar elementos.The IComparer implementation to use when comparing elements.

-o bien--or- null para usar la implementación de IComparable de cada elemento.null to use the IComparable implementation of each element.

Excepciones

El objeto Array de keys es multidimensional.The keysArray is multidimensional.

-o bien--or- El objeto Array de items es multidimensional.The itemsArray is multidimensional.

index es menor que el límite inferior de keys.index is less than the lower bound of keys.

-o bien--or- length es menor que cero.length is less than zero.

items no es null y el límite inferior de keys no coincide con el límite inferior de items.items is not null, and the lower bound of keys does not match the lower bound of items.

-o bien--or- items no es null y la longitud de keys es mayor que la longitud de items.items is not null, and the length of keys is greater than the length of items.

-o bien--or- index y length no especifican un intervalo válido en el objeto Array de keys.index and length do not specify a valid range in the keysArray.

-o bien--or- items no es null, y index y length no especifican un intervalo válido en el objeto Array de items.items is not null, and index and length do not specify a valid range in the itemsArray.

-o bien--or- La implementación de comparer produjo un error durante la ordenación.The implementation of comparer caused an error during the sort. Por ejemplo, es posible que comparer no devuelva 0 al comparar un elemento consigo mismo.For example, comparer might not return 0 when comparing an item with itself.

comparer es null, y uno o más elementos del objeto Array de keys no implementan la interfaz de IComparable.comparer is null, and one or more elements in the keysArray do not implement the IComparable interface.

Ejemplos

El ejemplo de código siguiente muestra cómo ordenar dos matrices asociadas, donde la primera matriz contiene las claves y la segunda matriz contiene los valores.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. Ordenaciones se realizan utilizando el comparador predeterminado y un comparador personalizado que invierte el criterio de ordenación.Sorts are done using the default comparer and a custom comparer that reverses the sort order. Tenga en cuenta que el resultado puede variar según la actual CultureInfo.Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

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

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

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

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

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

   }

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

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

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

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

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


/* 
This code produces the following output.

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

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

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

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

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

*/

Imports System
Imports System.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class 'myReverserClass


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub 'Main


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

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

   End Sub 'PrintKeysAndValues

End Class 'SamplesArray


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

Comentarios

Cada clave de la keys Array tiene un elemento correspondiente en el items Array.Each key in the keysArray has a corresponding item in the itemsArray. Cuando se vuelve a ubicar una clave durante la ordenación, el elemento correspondiente en el items Array del mismo modo se cambia de posición.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Por lo tanto, el items Array se ordenan según la disposición de las claves correspondientes en el keys Array.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Si comparer es null, cada clave dentro del intervalo especificado de elementos de la keys Array debe implementar la IComparable interfaz para poder realizar comparaciones con otras claves.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.

Puede ordenar si hay más elementos que las claves, pero no se ordenarán los elementos que no tengan ninguna de las claves correspondientes.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. No se puede ordenar si hay más teclas que los elementos; al hacerlo se inicia un ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

.NET Framework incluye predefinidos IComparer implementaciones se muestran en la tabla siguiente.The .NET Framework includes predefined IComparer implementations listed in the following table.

ImplementaciónImplementation DescripciónDescription
System.Collections.CaseInsensitiveComparer Compara los dos objetos, pero se realiza una comparación entre mayúsculas y minúsculas de cadenas.Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default Compara los dos objetos usando las convenciones de ordenación de la referencia cultural actual.Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant Compara los dos objetos usando las convenciones de ordenación de la referencia cultural invariable.Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default Compara dos objetos de tipo T utilizando el criterio de ordenación predeterminado del tipo.Compares two objects of type T by using the type's default sort order.

También puede admitir las comparaciones personalizadas, ya que proporciona una instancia de su propio IComparer implementación para el comparer parámetro.You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. El ejemplo hace esto definiendo un personalizado IComparer implementación que se invierte el criterio de ordenación predeterminado y realiza la comparación de cadenas entre mayúsculas y minúsculas.The example does this by defining a custom IComparer implementation that reverses the default sort order and performs case-insensitive string comparison.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es 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.

Notas a los autores de las llamadas

El .NET Framework 4 y versiones anteriores usan solo el algoritmo Quicksort.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. QuickSort identifica comparadores no válidos en algunas situaciones en que se inicia la operación de ordenación una IndexOutOfRangeException excepción e inicia un ArgumentException excepción al llamador.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. A partir de la .NET Framework 4.5.NET Framework 4.5, es posible que las operaciones de ordenación que anteriormente produjo ArgumentException no se iniciará una excepción, ya que los algoritmos de ordenación y heapsort de inserción no detectan un comparador no válido.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. En su mayor parte, esto se aplica a las matrices con menos de 16 elementos.For the most part, this applies to arrays with fewer than 16 elements.

Consulte también:

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

Ordena los elementos de un intervalo de elementos de una matriz Array unidimensional mediante el uso de la implementación de IComparable de cada elemento de la matriz 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

Parámetros

array
Array Array Array Array

Array unidimensional que se va a ordenar.The one-dimensional Array to sort.

index
Int32 Int32 Int32 Int32

Índice inicial del intervalo que se va a ordenar.The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

Número de elementos del intervalo que se va a ordenar.The number of elements in the range to sort.

Excepciones

array es multidimensional.array is multidimensional.

index es menor que el límite inferior de array.index is less than the lower bound of array.

-o bien--or- length es menor que cero.length is less than zero.

index y length no especifican un intervalo válido en array.index and length do not specify a valid range in array.

Uno o más elementos de la array no implementan la interfaz de IComparable.One or more elements in array do not implement the IComparable interface.

Ejemplos

El ejemplo de código siguiente muestra cómo ordenar los valores de un Array utilizando el comparador predeterminado y un comparador personalizado que invierte el criterio de ordenación.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. Tenga en cuenta que el resultado puede variar según la actual CultureInfo.Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

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

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

   Console::WriteLine();
}

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

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

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

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

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

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

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

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

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

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

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

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

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

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

Comentarios

Cada elemento dentro del intervalo especificado de elementos de array debe implementar la IComparable para realizar comparaciones con todos los elementos de interfaz de 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 el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es 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.

Consulte también:

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

Ordena un intervalo de elementos en un par de objetos Array unidimensionales (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera matriz Array usando la implementación de IComparable de cada clave.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)

Parámetros

keys
Array Array Array Array

La Array unidimensional que contiene las claves que se van a ordenar.The one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

Array unidimensional que contiene los elementos que corresponden a cada una de las claves del objeto keysArray.The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

-o bien--or- null para ordenar solo el objeto keysArray.null to sort only the keysArray.

index
Int32 Int32 Int32 Int32

Índice inicial del intervalo que se va a ordenar.The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

Número de elementos del intervalo que se va a ordenar.The number of elements in the range to sort.

Excepciones

El objeto Array de keys es multidimensional.The keysArray is multidimensional.

-o bien--or- El objeto Array de items es multidimensional.The itemsArray is multidimensional.

index es menor que el límite inferior de keys.index is less than the lower bound of keys.

-o bien--or- length es menor que cero.length is less than zero.

items no es null y la longitud de keys es mayor que la longitud de items.items is not null, and the length of keys is greater than the length of items.

-o bien--or- index y length no especifican un intervalo válido en el objeto Array de keys.index and length do not specify a valid range in the keysArray.

-o bien--or- items no es null, y index y length no especifican un intervalo válido en el objeto Array de items.items is not null, and index and length do not specify a valid range in the itemsArray.

Uno o más elementos del objeto Array de keys no implementan la interfaz IComparable.One or more elements in the keysArray do not implement the IComparable interface.

Ejemplos

El ejemplo de código siguiente muestra cómo ordenar dos matrices asociadas, donde la primera matriz contiene las claves y la segunda matriz contiene los valores.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. Ordenaciones se realizan utilizando el comparador predeterminado y un comparador personalizado que invierte el criterio de ordenación.Sorts are done using the default comparer and a custom comparer that reverses the sort order. Tenga en cuenta que el resultado puede variar según la actual CultureInfo.Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

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

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

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

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

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

   }

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

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

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

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

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


/* 
This code produces the following output.

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

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

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

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

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

*/

Imports System
Imports System.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class 'myReverserClass


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub 'Main


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

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

   End Sub 'PrintKeysAndValues

End Class 'SamplesArray


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

Comentarios

Cada clave de la keys Array tiene un elemento correspondiente en el items Array.Each key in the keysArray has a corresponding item in the itemsArray. Cuando se vuelve a ubicar una clave durante la ordenación, el elemento correspondiente en el items Array del mismo modo se cambia de posición.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Por lo tanto, el items Array se ordenan según la disposición de las claves correspondientes en el keys Array.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Cada clave dentro del intervalo especificado de elementos de la keys Array debe implementar la IComparable interfaz para poder realizar comparaciones con otras claves.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.

Puede ordenar si hay más elementos que las claves, pero no se ordenarán los elementos que no tengan ninguna de las claves correspondientes.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. No se puede ordenar si hay más teclas que los elementos; al hacerlo se inicia un ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es 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.

Consulte también:

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

Ordena los elementos de una matriz Array unidimensional usando la interfaz IComparer especificada.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

Parámetros

array
Array Array Array Array

Matriz unidimensional que se va a ordenar.The one-dimensional array to sort.

comparer
IComparer IComparer IComparer IComparer

Implementación que se usa al comparar elementos.The implementation to use when comparing elements.

-o bien--or- null para usar la implementación de IComparable de cada elemento.null to use the IComparable implementation of each element.

Excepciones

array es multidimensional.array is multidimensional.

comparer es null y uno o más elementos de la array no implementan la interfaz de IComparable.comparer is null, and one or more elements in array do not implement the IComparable interface.

La implementación de comparer produjo un error durante la ordenación.The implementation of comparer caused an error during the sort. Por ejemplo, es posible que comparer no devuelva 0 al comparar un elemento consigo mismo.For example, comparer might not return 0 when comparing an item with itself.

Ejemplos

El ejemplo siguiente ordena los valores en una matriz de cadenas utilizando el comparador predeterminado.The following example sorts the values in a string array by using the default comparer. También define un personalizado IComparer implementación denominada ReverseComparer que invierte el criterio de ordenación predeterminado de un objeto mientras se realiza una comparación de cadenas entre mayúsculas y minúsculas.It also defines a custom IComparer implementation named ReverseComparer that reverses an object's default sort order while performing a case-insensitive string comparison. Tenga en cuenta que la salida puede variar según la referencia cultural actual.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

Comentarios

Si comparer es null, cada elemento de array debe implementar la IComparable para realizar comparaciones con todos los elementos de interfaz de 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 el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es el 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.

.NET Framework incluye predefinidos IComparer implementaciones se muestran en la tabla siguiente.The .NET Framework includes predefined IComparer implementations listed in the following table.

ImplementaciónImplementation DescripciónDescription
System.Collections.CaseInsensitiveComparer Compara los dos objetos, pero se realiza una comparación entre mayúsculas y minúsculas de cadenas.Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default Compara los dos objetos usando las convenciones de ordenación de la referencia cultural actual.Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant Compara los dos objetos usando las convenciones de ordenación de la referencia cultural invariable.Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default Compara dos objetos de tipo T utilizando el criterio de ordenación predeterminado del tipo.Compares two objects of type T by using the type's default sort order.

También puede admitir las comparaciones personalizadas, ya que proporciona una instancia de su propio IComparer implementación para el comparer parámetro.You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. El ejemplo hace esto mediante la definición de un ReverseComparer clase que se invierte el criterio de ordenación predeterminado para las instancias de un tipo y realiza la comparación de cadenas entre mayúsculas y minúsculas.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.

Notas a los autores de las llamadas

El .NET Framework 4 y versiones anteriores usan solo el algoritmo Quicksort.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. QuickSort identifica comparadores no válidos en algunas situaciones en que se inicia la operación de ordenación una IndexOutOfRangeException excepción e inicia un ArgumentException excepción al llamador.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. A partir de la .NET Framework 4.5.NET Framework 4.5, es posible que las operaciones de ordenación que anteriormente produjo ArgumentException no se iniciará una excepción, ya que los algoritmos de ordenación y heapsort de inserción no detectan un comparador no válido.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. En su mayor parte, esto se aplica a las matrices con menos de 16 elementos.For the most part, this applies to arrays with fewer than 16 elements.

Consulte también:

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

Ordena un par de objetos Array unidimensionales (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera Array usando la IComparer. especificada.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)

Parámetros

keys
Array Array Array Array

La Array unidimensional que contiene las claves que se van a ordenar.The one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

Array unidimensional que contiene los elementos que corresponden a cada una de las claves del objeto keysArray.The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

-o bien--or- null para ordenar solo el objeto keysArray.null to sort only the keysArray.

comparer
IComparer IComparer IComparer IComparer

Implementación de IComparer que se va a usar al comparar elementos.The IComparer implementation to use when comparing elements.

-o bien--or- null para usar la implementación de IComparable de cada elemento.null to use the IComparable implementation of each element.

Excepciones

El objeto Array de keys es multidimensional.The keysArray is multidimensional.

-o bien--or- El objeto Array de items es multidimensional.The itemsArray is multidimensional.

items no es null y la longitud de keys es mayor que la longitud de items.items is not null, and the length of keys is greater than the length of items.

-o bien--or- La implementación de comparer produjo un error durante la ordenación.The implementation of comparer caused an error during the sort. Por ejemplo, es posible que comparer no devuelva 0 al comparar un elemento consigo mismo.For example, comparer might not return 0 when comparing an item with itself.

comparer es null, y uno o más elementos del objeto Array de keys no implementan la interfaz de IComparable.comparer is null, and one or more elements in the keysArray do not implement the IComparable interface.

Ejemplos

El ejemplo siguiente muestra cómo ordenar dos matrices asociadas, donde la primera matriz contiene las claves y la segunda matriz contiene los valores.The following example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. Ordenaciones se realizan utilizando el comparador predeterminado y un comparador personalizado que invierte el criterio de ordenación.Sorts are done using the default comparer and a custom comparer that reverses the sort order. Tenga en cuenta que el resultado puede variar según la actual CultureInfo.Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

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

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

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

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

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

   }

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

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

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

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

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


/* 
This code produces the following output.

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

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

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

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

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

*/

Imports System
Imports System.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class 'myReverserClass


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub 'Main


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

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

   End Sub 'PrintKeysAndValues

End Class 'SamplesArray


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

Comentarios

Cada clave de la keys Array tiene un elemento correspondiente en el items Array.Each key in the keysArray has a corresponding item in the itemsArray. Cuando se vuelve a ubicar una clave durante la ordenación, el elemento correspondiente en el items Array del mismo modo se cambia de posición.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Por lo tanto, el items Array se ordenan según la disposición de las claves correspondientes en el keys Array.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Si comparer es null, cada clave en el keys Array debe implementar la IComparable interfaz para poder realizar comparaciones con otras claves.If comparer is null, each key in the keysArray must implement the IComparable interface to be capable of comparisons with every other key.

Puede ordenar si hay más elementos que las claves, pero no se ordenarán los elementos que no tengan ninguna de las claves correspondientes.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. No se puede ordenar si hay más teclas que los elementos; al hacerlo se inicia un ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

.NET Framework incluye predefinidos IComparer implementaciones se muestran en la tabla siguiente.The .NET Framework includes predefined IComparer implementations listed in the following table.

ImplementaciónImplementation DescripciónDescription
System.Collections.CaseInsensitiveComparer Compara los dos objetos, pero se realiza una comparación entre mayúsculas y minúsculas de cadenas.Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default Compara los dos objetos usando las convenciones de ordenación de la referencia cultural actual.Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant Compara los dos objetos usando las convenciones de ordenación de la referencia cultural invariable.Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default Compara dos objetos de tipo T utilizando el criterio de ordenación predeterminado del tipo.Compares two objects of type T by using the type's default sort order.

También puede admitir las comparaciones personalizadas, ya que proporciona una instancia de su propio IComparer implementación para el comparer parámetro.You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. El ejemplo hace esto mediante la definición de un IComparer implementación que se invierte el criterio de ordenación predeterminado y realiza la comparación de cadenas entre mayúsculas y minúsculas.The example does this by defining an IComparer implementation that reverses the default sort order and performs case-insensitive string comparison.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es el 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.

Notas a los autores de las llamadas

El .NET Framework 4 y versiones anteriores usan solo el algoritmo Quicksort.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. QuickSort identifica comparadores no válidos en algunas situaciones en que se inicia la operación de ordenación una IndexOutOfRangeException excepción e inicia un ArgumentException excepción al llamador.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. A partir de la .NET Framework 4.5.NET Framework 4.5, es posible que las operaciones de ordenación que anteriormente produjo ArgumentException no se iniciará una excepción, ya que los algoritmos de ordenación y heapsort de inserción no detectan un comparador no válido.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. En su mayor parte, esto se aplica a las matrices con menos de 16 elementos.For the most part, this applies to arrays with fewer than 16 elements.

Consulte también:

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

Ordena un par de objetos Array unidimensionales (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera Array usando la implementación de IComparable de cada clave.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)

Parámetros

keys
Array Array Array Array

La Array unidimensional que contiene las claves que se van a ordenar.The one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

Array unidimensional que contiene los elementos que corresponden a cada una de las claves del objeto keysArray.The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

-o bien--or- null para ordenar solo el objeto keysArray.null to sort only the keysArray.

Excepciones

El objeto Array de keys es multidimensional.The keysArray is multidimensional.

-o bien--or- El objeto Array de items es multidimensional.The itemsArray is multidimensional.

itemsno es null y la longitud de keys es mayor que la longitud de items.items is not null, and the length of keys is greater than the length of items.

Uno o más elementos del objeto Array de keys no implementan la interfaz IComparable.One or more elements in the keysArray do not implement the IComparable interface.

Ejemplos

El ejemplo siguiente muestra cómo ordenar dos matrices asociadas, donde la primera matriz contiene las claves y la segunda matriz contiene los valores.The following example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. Ordenaciones se realizan utilizando el comparador predeterminado y un comparador personalizado que invierte el criterio de ordenación.Sorts are done using the default comparer and a custom comparer that reverses the sort order. Tenga en cuenta que el resultado puede variar según la actual CultureInfo.Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

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

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

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

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

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

   }

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

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

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

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

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


/* 
This code produces the following output.

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

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

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

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

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

*/

Imports System
Imports System.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class 'myReverserClass


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub 'Main


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

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

   End Sub 'PrintKeysAndValues

End Class 'SamplesArray


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

Comentarios

Cada clave de la keys Array tiene un elemento correspondiente en el items Array.Each key in the keysArray has a corresponding item in the itemsArray. Cuando se vuelve a ubicar una clave durante la ordenación, el elemento correspondiente en el items Array del mismo modo se cambia de posición.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Por lo tanto, el items Array se ordenan según la disposición de las claves correspondientes en el keys Array.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Cada clave de la keys Array debe implementar la IComparable interfaz para poder realizar comparaciones con otras claves.Each key in the keysArray must implement the IComparable interface to be capable of comparisons with every other key.

Puede ordenar si hay más elementos que las claves, pero no se ordenarán los elementos que no tengan ninguna de las claves correspondientes.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. No se puede ordenar si hay más teclas que los elementos; al hacerlo se inicia un ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es el 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.

Consulte también:

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

Ordena los elementos de toda una matriz Array unidimensional usando la implementación de IComparable de cada elemento de la matriz 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

Parámetros

array
Array Array Array Array

Array unidimensional que se va a ordenar.The one-dimensional Array to sort.

Excepciones

array es multidimensional.array is multidimensional.

Uno o más elementos de la array no implementan la interfaz de IComparable.One or more elements in array do not implement the IComparable interface.

Ejemplos

El ejemplo de código siguiente muestra cómo ordenar los valores de un Array utilizando el comparador predeterminado y un comparador personalizado que invierte el criterio de ordenación.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. Tenga en cuenta que el resultado puede variar según la actual CultureInfo.Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

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

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

   Console::WriteLine();
}

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

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

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

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

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

/* 
This code produces the following output.

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

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

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

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

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

*/
using System;
using System.Collections;

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

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

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

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

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

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

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

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

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

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

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

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

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

Comentarios

Cada elemento de array debe implementar la IComparable para realizar comparaciones con todos los elementos de interfaz de array.Each element of array must implement the IComparable interface to be capable of comparisons with every other element in array.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es el 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.

Consulte también:

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

Ordena los elementos de toda una matriz Array usando la implementación de la interfaz genérica IComparable<T> de cada elemento de 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())

Parámetros de tipo

T

Tipo de los elementos de la matriz.The type of the elements of the array.

Parámetros

array
T[]

Array unidimensional de base cero que se va a ordenar.The one-dimensional, zero-based Array to sort.

Excepciones

Uno o más elementos de array no implementan la interfaz genérica IComparable<T>.One or more elements in array do not implement the IComparable<T> generic interface.

Ejemplos

En el ejemplo de código siguiente se muestra el Sort<T>(T[]) sobrecarga del método genérico y el BinarySearch<T>(T[], T) sobrecarga del método genérico.The following code example demonstrates the Sort<T>(T[]) generic method overload and the BinarySearch<T>(T[], T) generic method overload. Se crea una matriz de cadenas, sin ningún orden determinado.An array of strings is created, in no particular order.

La matriz se muestra, ordenan y volverá a mostrar.The array is displayed, sorted, and displayed again.

Nota

Las llamadas a la Sort y BinarySearch métodos genéricos no parece diferentes de las llamadas a sus homólogas no genéricas, ya que Visual Basic, C# y C++ deducen el tipo de parámetro de tipo genérico del tipo del primer argumento.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 usas el Ildasm.exe (Desensamblador de IL) para examinar el lenguaje intermedio de Microsoft (MSIL), puede ver que se llama a los métodos genéricos.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.

El BinarySearch<T>(T[], T) sobrecarga del método genérico, a continuación, se usa para buscar dos cadenas, una que no está en la matriz y uno que es.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. La matriz y el valor devuelto de la BinarySearch método se pasan a la ShowWhere método genérico, que muestra el valor de índice si se encuentra la cadena y, en caso contrario, los elementos de la cadena de búsqueda pudieran estar incluidos entre si estuviera en la matriz.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. El índice es negativo si la cadena no es n la matriz, por lo que la ShowWhere método toma el complemento bit a bit (el ~ operador en C# y Visual C++, Xor -1 en Visual Basic) para obtener el índice del primer elemento en la lista que es mayor que la búsqueda de Cade NG.The index is negative if the string is not n the array, so the ShowWhere method takes the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) to obtain the index of the first element in the list that is larger than the search string.

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

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

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

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

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

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

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

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

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

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

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

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

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

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

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

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

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

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

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

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

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

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

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

Public Class Example

    Public Shared Sub Main()

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

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

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

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

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

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

    End Sub

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

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

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

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

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

    End Sub

End Class

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

Comentarios

Cada elemento de array debe implementar la IComparable<T> interfaz genérica para poder realizar comparaciones con todos los elementos de array.Each element of array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es el 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.

Consulte también:

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

Ordena los elementos de una Array usando la interfaz genérica IComparer<T> especificada.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))

Parámetros de tipo

T

Tipo de los elementos de la matriz.The type of the elements of the array.

Parámetros

array
T[]

Array unidimensional de base cero que se va a ordenar.The one-dimensional, zero-base Array to sort

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

La implementación de la interfaz genérica IComparer<T> que se va a usar al comparar elementos o null para usar la implementación de la interfaz genérica IComparable<T> de cada elemento.The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

Excepciones

comparer es null y uno o varios elementos de array no implementan la interfaz genérica IComparable<T>.comparer is null, and one or more elements in array do not implement the IComparable<T> generic interface.

La implementación de comparer produjo un error durante la ordenación.The implementation of comparer caused an error during the sort. Por ejemplo, es posible que comparer no devuelva 0 al comparar un elemento consigo mismo.For example, comparer might not return 0 when comparing an item with itself.

Ejemplos

En el ejemplo de código siguiente se muestra el Sort<T>(T[], IComparer<T>) sobrecarga del método genérico y el BinarySearch<T>(T[], T, IComparer<T>) sobrecarga del método genérico.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.

El ejemplo de código define un comparador alternativo para las cadenas, denominado ReverseCompare, que implementa el IComparer<string> (IComparer(Of String) en Visual Basic, IComparer<String^> en Visual C++) interfaz genérica.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. Las llamadas de comparador el CompareTo(String) método, invertir el orden de los términos de la comparación para que las cadenas ordenen alta o baja, en lugar de bajo a alto.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.

La matriz se muestra, ordenan y volverá a mostrar.The array is displayed, sorted, and displayed again. Las matrices deben estar ordenadas para poder usar el BinarySearch método.Arrays must be sorted in order to use the BinarySearch method.

Nota

Las llamadas a la Sort<T>(T[], IComparer<T>) y BinarySearch<T>(T[], T, IComparer<T>) métodos genéricos no parece diferentes de las llamadas a sus homólogas no genéricas, ya que Visual Basic, C# y C++ deducen el tipo de parámetro de tipo genérico del tipo del primer argumento.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 usas el Ildasm.exe (Desensamblador de IL) para examinar el lenguaje intermedio de Microsoft (MSIL), puede ver que se llama a los métodos genéricos.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.

El BinarySearch<T>(T[], T, IComparer<T>) sobrecarga del método genérico, a continuación, se usa para buscar dos cadenas, una que no está en la matriz y uno que es.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. La matriz y el valor devuelto de la BinarySearch<T>(T[], T, IComparer<T>) método se pasan a la ShowWhere método genérico, que muestra el valor de índice si se encuentra la cadena y, en caso contrario, los elementos de la cadena de búsqueda pudieran estar incluidos entre si estuviera en la matriz.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. El índice es negativo si la cadena no es n la matriz, por lo que la ShowWhere método toma el complemento bit a bit (el ~ operador en C# y Visual C++, Xor -1 en Visual Basic) para obtener el índice del primer elemento en la lista que es mayor que la búsqueda de Cade NG.The index is negative if the string is not n the array, so the ShowWhere method takes the bitwise complement (the ~ operator in C# and Visual C++, Xor -1 in Visual Basic) to obtain the index of the first element in the list that is larger than the search string.

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

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus

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

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

    End Sub

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

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

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

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

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

    End Sub

End Class

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

Comentarios

Si comparer es null, cada elemento de array debe implementar la IComparable<T> interfaz genérica para poder realizar comparaciones con todos los elementos de 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 el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es el 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.

Notas a los autores de las llamadas

El .NET Framework 4 y versiones anteriores usan solo el algoritmo Quicksort.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. QuickSort identifica comparadores no válidos en algunas situaciones en que se inicia la operación de ordenación una IndexOutOfRangeException excepción e inicia un ArgumentException excepción al llamador.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. A partir de la .NET Framework 4.5.NET Framework 4.5, es posible que las operaciones de ordenación que anteriormente produjo ArgumentException no se iniciará una excepción, ya que los algoritmos de ordenación y heapsort de inserción no detectan un comparador no válido.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. En su mayor parte, esto se aplica a las matrices con menos de 16 elementos.For the most part, this applies to arrays with fewer than 16 elements.

Consulte también:

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

Ordena los elementos de una Array usando el Comparison<T> especificado.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))

Parámetros de tipo

T

Tipo de los elementos de la matriz.The type of the elements of the array.

Parámetros

array
T[]

Array unidimensional, basado en cero, que se va a ordenarThe one-dimensional, zero-based Array to sort

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

Comparison<T> que se va a utilizar al comparar elementos.The Comparison<T> to use when comparing elements.

Excepciones

El valor de array es null.array is null.

-o bien--or- El valor de comparison es null.comparison is null.

La implementación de comparison ha producido un error durante la ordenación.The implementation of comparison caused an error during the sort. Por ejemplo, es posible que comparison no devuelva 0 al comparar un elemento consigo mismo.For example, comparison might not return 0 when comparing an item with itself.

Ejemplos

En el ejemplo de código siguiente se muestra el Sort(Comparison<T>) sobrecarga del método.The following code example demonstrates the Sort(Comparison<T>) method overload.

El ejemplo de código define un método de comparación alternativo para las cadenas, denominado CompareDinosByLength.The code example defines an alternative comparison method for strings, named CompareDinosByLength. Este método funciona del siguiente modo: En primer lugar, se comprueba si la comparaciónnull, y una referencia nula se considera menor que un valor no null.This method works as follows: First, the comparands are tested fornull, and a null reference is treated as less than a non-null. En segundo lugar, se comparan las longitudes de cadena, y se considera que la cadena más larga para que sea mayor.Second, the string lengths are compared, and the longer string is deemed to be greater. En tercer lugar, si las longitudes son iguales, se usa la comparación de cadenas normales.Third, if the lengths are equal, ordinary string comparison is used.

Se crea una matriz de cadenas y se rellena con cuatro cadenas, sin ningún orden determinado.A array of strings is created and populated with four strings, in no particular order. La lista también incluye una cadena vacía y una referencia nula.The list also includes an empty string and a null reference. Se muestra la lista, se ordena usando un Comparison<T> delegado genérico que representa el CompareDinosByLength método y volverá a mostrar.The list is displayed, sorted using a Comparison<T> generic delegate representing the CompareDinosByLength method, and displayed again.

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

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

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

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

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

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

}

/* This code example produces the following output:

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

Sort with generic Comparison<String^> delegate:

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

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

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

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

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

    }

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

/* This code example produces the following output:

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

Sort with generic Comparison<string> delegate:

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

Public Class Example

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

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

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

    End Function

    Public Shared Sub Main()

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

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

    End Sub

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

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

Comentarios

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método usa el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es el 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.

Notas a los autores de las llamadas

El .NET Framework 4 y versiones anteriores usan solo el algoritmo Quicksort.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. QuickSort identifica comparadores no válidos en algunas situaciones en que se inicia la operación de ordenación una IndexOutOfRangeException excepción e inicia un ArgumentException excepción al llamador.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. A partir de la .NET Framework 4.5.NET Framework 4.5, es posible que las operaciones de ordenación que anteriormente produjo ArgumentException no se iniciará una excepción, ya que los algoritmos de ordenación y heapsort de inserción no detectan un comparador no válido.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. En su mayor parte, esto se aplica a las matrices con menos de 16 elementos.For the most part, this applies to arrays with fewer than 16 elements.

Consulte también:

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

Ordena los elementos en un intervalo de elementos en una Array mediante la implementación de interfaz genérica IComparable<T> de cada elemento de la 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)

Parámetros de tipo

T

Tipo de los elementos de la matriz.The type of the elements of the array.

Parámetros

array
T[]

Array unidimensional, basado en cero, que se va a ordenarThe one-dimensional, zero-based Array to sort

index
Int32 Int32 Int32 Int32

Índice inicial del intervalo que se va a ordenar.The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

Número de elementos del intervalo que se va a ordenar.The number of elements in the range to sort.

Excepciones

index es menor que el límite inferior de array.index is less than the lower bound of array.

-o bien--or- length es menor que cero.length is less than zero.

index y length no especifican un intervalo válido en array.index and length do not specify a valid range in array.

Uno o más elementos de array no implementan la interfaz genérica IComparable<T>.One or more elements in array do not implement the IComparable<T> generic interface.

Ejemplos

En el ejemplo de código siguiente se muestra el Sort<T>(T[], Int32, Int32) sobrecarga del método genérico y el Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) sobrecarga del método genérico para ordenar un intervalo en una matriz.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.

El ejemplo de código define un comparador alternativo para las cadenas, denominado ReverseCompare, que implementa el IComparer<string> (IComparer(Of String) en Visual Basic, IComparer<String^> en Visual C++) interfaz genérica.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. Las llamadas de comparador el CompareTo(String) método, invertir el orden de los términos de la comparación para que las cadenas ordenen alta o baja, en lugar de bajo a alto.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.

El ejemplo de código se crea y muestra una matriz de nombres de dinosaurios, que consta de tres herbívoros seguidos por tres carnívoros (tiranosaurios, para ser precisos).The code example creates and displays an array of dinosaur names, consisting of three herbivores followed by three carnivores (tyrannosaurids, to be precise). El Sort<T>(T[], Int32, Int32) sobrecarga del método genérico se usa para ordenar los tres últimos elementos de la matriz, que se muestra a continuación.The Sort<T>(T[], Int32, Int32) generic method overload is used to sort the last three elements of the array, which is then displayed. El Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) se usa la sobrecarga del método genérico con ReverseCompare para ordenar los tres últimos elementos en orden inverso.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. Los dinosaurios exhaustivamente confundirse aparecerán de nuevo.The thoroughly confused dinosaurs are displayed again.

Nota

Las llamadas a la Sort<T>(T[], IComparer<T>) y BinarySearch<T>(T[], T, IComparer<T>) métodos genéricos no parece diferentes de las llamadas a sus homólogas no genéricas, ya que Visual Basic, C# y C++ deducen el tipo de parámetro de tipo genérico del tipo del primer argumento.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 usas el Ildasm.exe (Desensamblador de IL) para examinar el lenguaje intermedio de Microsoft (MSIL), puede ver que se llama a los métodos genéricos.If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

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

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

    End Sub

End Class

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

Comentarios

Cada elemento dentro del intervalo especificado de elementos de array debe implementar la IComparable<T> interfaz genérica para poder realizar comparaciones con todos los elementos de 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 el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es 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.

Consulte también:

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

Ordena los elementos de un intervalo de elementos en un elemento Array mediante la interfaz genérica IComparer<T> especificada.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))

Parámetros de tipo

T

Tipo de los elementos de la matriz.The type of the elements of the array.

Parámetros

array
T[]

Array unidimensional de base cero que se va a ordenar.The one-dimensional, zero-based Array to sort.

index
Int32 Int32 Int32 Int32

Índice inicial del intervalo que se va a ordenar.The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

Número de elementos del intervalo que se va a ordenar.The number of elements in the range to sort.

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

La implementación de la interfaz genérica IComparer<T> que se va a usar al comparar elementos o null para usar la implementación de la interfaz genérica IComparable<T> de cada elemento.The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

Excepciones

index es menor que el límite inferior de array.index is less than the lower bound of array.

-o bien--or- length es menor que cero.length is less than zero.

index y length no especifican un intervalo válido en array.index and length do not specify a valid range in array.

-o bien--or- La implementación de comparer produjo un error durante la ordenación.The implementation of comparer caused an error during the sort. Por ejemplo, es posible que comparer no devuelva 0 al comparar un elemento consigo mismo.For example, comparer might not return 0 when comparing an item with itself.

comparer es null y uno o varios elementos de array no implementan la interfaz genérica IComparable<T>.comparer is null, and one or more elements in array do not implement the IComparable<T> generic interface.

Ejemplos

En el ejemplo de código siguiente se muestra el Sort<T>(T[], Int32, Int32) sobrecarga del método genérico y el Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) sobrecarga del método genérico para ordenar un intervalo en una matriz.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.

El ejemplo de código define un comparador alternativo para las cadenas, denominado ReverseCompare, que implementa el IComparer<string> (IComparer(Of String) en Visual Basic, IComparer<String^> en Visual C++) interfaz genérica.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. Las llamadas de comparador el CompareTo(String) método, invertir el orden de los términos de la comparación para que las cadenas ordenen alta o baja, en lugar de bajo a alto.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.

El ejemplo de código se crea y muestra una matriz de nombres de dinosaurios, que consta de tres herbívoros seguidos por tres carnívoros (tiranosaurios, para ser precisos).The code example creates and displays an array of dinosaur names, consisting of three herbivores followed by three carnivores (tyrannosaurids, to be precise). El Sort<T>(T[], Int32, Int32) sobrecarga del método genérico se usa para ordenar los tres últimos elementos de la matriz, que se muestra a continuación.The Sort<T>(T[], Int32, Int32) generic method overload is used to sort the last three elements of the array, which is then displayed. El Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) se usa la sobrecarga del método genérico con ReverseCompare para ordenar los tres últimos elementos en orden inverso.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. Los dinosaurios exhaustivamente confundirse aparecerán de nuevo.The thoroughly confused dinosaurs are displayed again.

Nota

Las llamadas a la Sort<T>(T[], IComparer<T>) y BinarySearch<T>(T[], T, IComparer<T>) métodos genéricos no parece diferentes de las llamadas a sus homólogas no genéricas, ya que Visual Basic, C# y C++ deducen el tipo de parámetro de tipo genérico del tipo del primer argumento.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 usas el Ildasm.exe (Desensamblador de IL) para examinar el lenguaje intermedio de Microsoft (MSIL), puede ver que se llama a los métodos genéricos.If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

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

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

    End Sub

End Class

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

Comentarios

Si comparer es null, cada elemento dentro del intervalo especificado de elementos de array debe implementar la IComparable<T> interfaz genérica para poder realizar comparaciones con todos los elementos de 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 el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es 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.

Notas a los autores de las llamadas

El .NET Framework 4 y versiones anteriores usan solo el algoritmo Quicksort.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. QuickSort identifica comparadores no válidos en algunas situaciones en que se inicia la operación de ordenación una IndexOutOfRangeException excepción e inicia un ArgumentException excepción al llamador.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. A partir de la .NET Framework 4.5.NET Framework 4.5, es posible que las operaciones de ordenación que anteriormente produjo ArgumentException no se iniciará una excepción, ya que los algoritmos de ordenación y heapsort de inserción no detectan un comparador no válido.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. En su mayor parte, esto se aplica a las matrices con menos de 16 elementos.For the most part, this applies to arrays with fewer than 16 elements.

Consulte también:

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

Ordena un par de objetos Array (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera Array usando la implementación de la interfaz genérica IComparable<T> de cada clave.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())

Parámetros de tipo

TKey

Tipo de los elementos de la matriz de claves.The type of the elements of the key array.

TValue

Tipo de los elementos de la matriz de elementos.The type of the elements of the items array.

Parámetros

keys
TKey[]

Array unidimensional de base cero que contiene las claves que se van a ordenar.The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

Array unidimensional de base cero que contiene los elementos que se corresponden con las claves de keys o null para ordenar solo keys.The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

Excepciones

items no es null y el límite inferior de keys no coincide con el límite inferior de items.items is not null, and the lower bound of keys does not match the lower bound of items.

-o bien--or- items no es null y la longitud de keys es mayor que la longitud de items.items is not null, and the length of keys is greater than the length of items.

Uno o más elementos del objeto Array de keys no implementan la interfaz genérica IComparable<T>.One or more elements in the keysArray do not implement the IComparable<T> generic interface.

Ejemplos

En el ejemplo de código siguiente se muestra el Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), y Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) sobrecargas de método genérico, para ordenar pares de matrices que representan las claves y valores.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.

El ejemplo de código define un comparador alternativo para las cadenas, denominado ReverseCompare, que implementa el IComparer<string> (IComparer(Of String) en Visual Basic, IComparer<String^> en Visual C++) interfaz genérica.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. Las llamadas de comparador el CompareTo(String) método, invertir el orden de los términos de la comparación para que las cadenas ordenen alta o baja, en lugar de bajo a alto.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.

El ejemplo de código se crea y muestra una matriz de nombres de dinosaurios (las claves) y una matriz de enteros que representa la longitud máxima de cada dinosaurio en metros (los valores).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). Las matrices, a continuación, se ordena y se muestran varias veces:The arrays are then sorted and displayed several times:

Nota

Las llamadas a los métodos genéricos no parece diferentes de las llamadas a sus homólogas no genéricas, ya que Visual Basic, C# y C++ deducen el tipo de parámetro de tipo genérico del tipo de los dos primeros argumentos.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 usas el Ildasm.exe (Desensamblador de IL) para examinar el lenguaje intermedio de Microsoft (MSIL), puede ver que se llama a los métodos genéricos.If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

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

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs() As String = { _
            "Seismosaurus", _
            "Chasmosaurus", _
            "Coelophysis", _
            "Mamenchisaurus", _
            "Caudipteryx", _
            "Cetiosaurus"  }

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

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

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

    End Sub

End Class

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

Comentarios

Cada clave de la keys Array tiene un elemento correspondiente en el items Array.Each key in the keysArray has a corresponding item in the itemsArray. Cuando se vuelve a ubicar una clave durante la ordenación, el elemento correspondiente en el items Array del mismo modo se cambia de posición.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Por lo tanto, el items Array se ordenan según la disposición de las claves correspondientes en el keys Array.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Cada clave de la keys Array debe implementar la IComparable<T> interfaz genérica para poder realizar comparaciones con otras claves.Each key in the keysArray must implement the IComparable<T> generic interface to be capable of comparisons with every other key.

Puede ordenar si hay más elementos que las claves, pero no se ordenarán los elementos que no tengan ninguna de las claves correspondientes.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. No se puede ordenar si hay más teclas que los elementos; al hacerlo se inicia un ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es el 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.

Consulte también:

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

Ordena un par de objetos Array (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera matriz Array usando la interfaz genérica IComparer<T> especificada.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))

Parámetros de tipo

TKey

Tipo de los elementos de la matriz de claves.The type of the elements of the key array.

TValue

Tipo de los elementos de la matriz de elementos.The type of the elements of the items array.

Parámetros

keys
TKey[]

Array unidimensional de base cero que contiene las claves que se van a ordenar.The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

Array unidimensional de base cero que contiene los elementos que se corresponden con las claves de keys o null para ordenar solo 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>

La implementación de la interfaz genérica IComparer<T> que se va a usar al comparar elementos o null para usar la implementación de la interfaz genérica IComparable<T> de cada elemento.The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

Excepciones

items no es null y el límite inferior de keys no coincide con el límite inferior de items.items is not null, and the lower bound of keys does not match the lower bound of items.

-o bien--or- items no es null y la longitud de keys es mayor que la longitud de items.items is not null, and the length of keys is greater than the length of items.

-o bien--or- La implementación de comparer produjo un error durante la ordenación.The implementation of comparer caused an error during the sort. Por ejemplo, es posible que comparer no devuelva 0 al comparar un elemento consigo mismo.For example, comparer might not return 0 when comparing an item with itself.

comparer es null y uno o más elementos del objeto Array de keys no implementan la interfaz genérica IComparable<T>.comparer is null, and one or more elements in the keysArray do not implement the IComparable<T> generic interface.

Ejemplos

En el ejemplo de código siguiente se muestra el 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), y Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) sobrecargas de método genérico, para ordenar pares de matrices que representan las claves y valores.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.

El ejemplo de código define un comparador alternativo para las cadenas, denominado ReverseCompare, que implementa el IComparer<string> (IComparer(Of String) en Visual Basic, IComparer<String^> en Visual C++) interfaz genérica.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. Las llamadas de comparador el CompareTo(String) método, invertir el orden de los términos de la comparación para que las cadenas ordenen alta o baja, en lugar de bajo a alto.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.

El ejemplo de código se crea y muestra una matriz de nombres de dinosaurios (las claves) y una matriz de enteros que representa la longitud máxima de cada dinosaurio en metros (los valores).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). Las matrices, a continuación, se ordena y se muestran varias veces:The arrays are then sorted and displayed several times:

Nota

Las llamadas a los métodos genéricos no parece diferentes de las llamadas a sus homólogas no genéricas, ya que Visual Basic, C# y C++ deducen el tipo de parámetro de tipo genérico del tipo de los dos primeros argumentos.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 usas el Ildasm.exe (Desensamblador de IL) para examinar el lenguaje intermedio de Microsoft (MSIL), puede ver que se llama a los métodos genéricos.If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

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

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs() As String = { _
            "Seismosaurus", _
            "Chasmosaurus", _
            "Coelophysis", _
            "Mamenchisaurus", _
            "Caudipteryx", _
            "Cetiosaurus"  }

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

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

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

    End Sub

End Class

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

Comentarios

Cada clave de la keys Array tiene un elemento correspondiente en el items Array.Each key in the keysArray has a corresponding item in the itemsArray. Cuando se vuelve a ubicar una clave durante la ordenación, el elemento correspondiente en el items Array del mismo modo se cambia de posición.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Por lo tanto, el items Array se ordenan según la disposición de las claves correspondientes en el keys Array.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Si comparer es null, cada clave en el keys Array debe implementar la IComparable<T> interfaz genérica para poder realizar comparaciones con otras claves.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.

Puede ordenar si hay más elementos que las claves, pero no se ordenarán los elementos que no tengan ninguna de las claves correspondientes.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. No se puede ordenar si hay más teclas que los elementos; al hacerlo se inicia un ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es el 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.

Notas a los autores de las llamadas

El .NET Framework 4 y versiones anteriores usan solo el algoritmo Quicksort.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. QuickSort identifica comparadores no válidos en algunas situaciones en que se inicia la operación de ordenación una IndexOutOfRangeException excepción e inicia un ArgumentException excepción al llamador.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. A partir de la .NET Framework 4.5.NET Framework 4.5, es posible que las operaciones de ordenación que anteriormente produjo ArgumentException no se iniciará una excepción, ya que los algoritmos de ordenación y heapsort de inserción no detectan un comparador no válido.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. En su mayor parte, esto se aplica a las matrices con menos de 16 elementos.For the most part, this applies to arrays with fewer than 16 elements.

Consulte también:

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

Ordena un intervalo de elementos en un par de objetos Array (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera matriz Array usando la implementación de la interfaz genérica IComparable<T> de cada clave.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)

Parámetros de tipo

TKey

Tipo de los elementos de la matriz de claves.The type of the elements of the key array.

TValue

Tipo de los elementos de la matriz de elementos.The type of the elements of the items array.

Parámetros

keys
TKey[]

Array unidimensional de base cero que contiene las claves que se van a ordenar.The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

Matriz Array unidimensional de base cero que contiene los elementos que se corresponden con las claves del parámetro keys; o null para ordenar solo 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 Int32 Int32 Int32

Índice inicial del intervalo que se va a ordenar.The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

Número de elementos del intervalo que se va a ordenar.The number of elements in the range to sort.

Excepciones

index es menor que el límite inferior de keys.index is less than the lower bound of keys.

-o bien--or- length es menor que cero.length is less than zero.

items no es null y el límite inferior de keys no coincide con el límite inferior de items.items is not null, and the lower bound of keys does not match the lower bound of items.

-o bien--or- items no es null y la longitud de keys es mayor que la longitud de items.items is not null, and the length of keys is greater than the length of items.

-o bien--or- index y length no especifican un intervalo válido en el objeto Array de keys.index and length do not specify a valid range in the keysArray.

-o bien--or- items no es null, y index y length no especifican un intervalo válido en el objeto Array de items.items is not null, and index and length do not specify a valid range in the itemsArray.

Uno o más elementos del objeto Array de keys no implementan la interfaz genérica IComparable<T>.One or more elements in the keysArray do not implement the IComparable<T> generic interface.

Ejemplos

En el ejemplo de código siguiente se muestra el 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 >, y Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) sobrecargas de método genérico para ordenar pares de matrices que representan las claves y valores.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.

El ejemplo de código define un comparador alternativo para las cadenas, denominado ReverseCompare, que implementa el IComparer<string> (IComparer(Of String) en Visual Basic, IComparer<String^> en Visual C++) interfaz genérica.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. Las llamadas de comparador el CompareTo(String) método, invertir el orden de los términos de la comparación para que las cadenas ordenen alta o baja, en lugar de bajo a alto.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.

El ejemplo de código se crea y muestra una matriz de nombres de dinosaurios (las claves) y una matriz de enteros que representa la longitud máxima de cada dinosaurio en metros (los valores).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). Las matrices, a continuación, se ordena y se muestran varias veces:The arrays are then sorted and displayed several times:

Nota

Las llamadas a los métodos genéricos no parece diferentes de las llamadas a sus homólogas no genéricas, ya que Visual Basic, C# y C++ deducen el tipo de parámetro de tipo genérico del tipo de los dos primeros argumentos.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 usas el Ildasm.exe (Desensamblador de IL) para examinar el lenguaje intermedio de Microsoft (MSIL), puede ver que se llama a los métodos genéricos.If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

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

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs() As String = { _
            "Seismosaurus", _
            "Chasmosaurus", _
            "Coelophysis", _
            "Mamenchisaurus", _
            "Caudipteryx", _
            "Cetiosaurus"  }

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

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

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

    End Sub

End Class

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

Comentarios

Cada clave de la keys Array tiene un elemento correspondiente en el items Array.Each key in the keysArray has a corresponding item in the itemsArray. Cuando se vuelve a ubicar una clave durante la ordenación, el elemento correspondiente en el items Array del mismo modo se cambia de posición.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Por lo tanto, el items Array se ordenan según la disposición de las claves correspondientes en el keys Array.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Cada clave dentro del intervalo especificado de elementos de la keys Array debe implementar la IComparable<T> interfaz genérica para poder realizar comparaciones con otras claves.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.

Puede ordenar si hay más elementos que las claves, pero no se ordenarán los elementos que no tengan ninguna de las claves correspondientes.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. No se puede ordenar si hay más teclas que los elementos; al hacerlo se inicia un ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es 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.

Consulte también:

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

Ordena un intervalo de elementos de un par de objetos Array (uno contiene las claves y el otro contiene los elementos correspondientes) en función de las claves de la primera matriz Array usando la interfaz genérica IComparer<T> especificada.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))

Parámetros de tipo

TKey

Tipo de los elementos de la matriz de claves.The type of the elements of the key array.

TValue

Tipo de los elementos de la matriz de elementos.The type of the elements of the items array.

Parámetros

keys
TKey[]

Array unidimensional de base cero que contiene las claves que se van a ordenar.The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

Matriz Array unidimensional de base cero que contiene los elementos que se corresponden con las claves del parámetro keys; o null para ordenar solo 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 Int32 Int32 Int32

Índice inicial del intervalo que se va a ordenar.The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

Número de elementos del intervalo que se va a ordenar.The number of elements in the range to sort.

comparer
IComparer<TKey>

La implementación de la interfaz genérica IComparer<T> que se va a usar al comparar elementos o null para usar la implementación de la interfaz genérica IComparable<T> de cada elemento.The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

Excepciones

index es menor que el límite inferior de keys.index is less than the lower bound of keys.

-o bien--or- length es menor que cero.length is less than zero.

items no es null y el límite inferior de keys no coincide con el límite inferior de items.items is not null, and the lower bound of keys does not match the lower bound of items.

-o bien--or- items no es null y la longitud de keys es mayor que la longitud de items.items is not null, and the length of keys is greater than the length of items.

-o bien--or- index y length no especifican un intervalo válido en el objeto Array de keys.index and length do not specify a valid range in the keysArray.

-o bien--or- items no es null, y index y length no especifican un intervalo válido en el objeto Array de items.items is not null, and index and length do not specify a valid range in the itemsArray.

-o bien--or- La implementación de comparer produjo un error durante la ordenación.The implementation of comparer caused an error during the sort. Por ejemplo, es posible que comparer no devuelva 0 al comparar un elemento consigo mismo.For example, comparer might not return 0 when comparing an item with itself.

comparer es null y uno o más elementos del objeto Array de keys no implementan la interfaz genérica IComparable<T>.comparer is null, and one or more elements in the keysArray do not implement the IComparable<T> generic interface.

Ejemplos

En el ejemplo de código siguiente se muestra el Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), y [], 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 > sobrecargas de método genérico, para ordenar pares de matrices que representan las claves y valores.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.

El ejemplo de código define un comparador alternativo para las cadenas, denominado ReverseCompare, que implementa el IComparer<string>(IComparer(Of String) en Visual Basic, IComparer<String^> en Visual C++) interfaz genérica.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. Las llamadas de comparador el CompareTo(String) método, invertir el orden de los términos de la comparación para que las cadenas ordenen alta o baja, en lugar de bajo a alto.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.

El ejemplo de código se crea y muestra una matriz de nombres de dinosaurios (las claves) y una matriz de enteros que representa la longitud máxima de cada dinosaurio en metros (los valores).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). Las matrices, a continuación, se ordena y se muestran varias veces:The arrays are then sorted and displayed several times:

  • El Sort<TKey,TValue>(TKey[], TValue[]) sobrecarga se utiliza para ordenar ambas matrices en orden de los nombres de dinosaurios de la primera matriz.The Sort<TKey,TValue>(TKey[], TValue[]) overload is used to sort both arrays in order of the dinosaur names in the first array.

  • El Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) sobrecarga y una instancia de ReverseCompare se usan para invertir el criterio de ordenación de las matrices emparejadas.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.

  • El Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) sobrecarga se utiliza para ordenar los tres últimos elementos de ambas matrices.The Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) overload is used to sort the last three elements of both arrays.

  • El [], 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 > sobrecarga se utiliza para ordenar los tres últimos elementos de ambas matrices en orden inverso.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.

Nota

Las llamadas a los métodos genéricos no parece diferentes de las llamadas a sus homólogas no genéricas, ya que Visual Basic, C# y C++ deducen el tipo de parámetro de tipo genérico del tipo de los dos primeros argumentos.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 usas el Ildasm.exe (Desensamblador de IL) para examinar el lenguaje intermedio de Microsoft (MSIL), puede ver que se llama a los métodos genéricos.If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

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

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

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

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

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

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

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

    ReverseComparer^ rc = gcnew ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

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

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

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

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

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

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

        ReverseComparer rc = new ReverseComparer();

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

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

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

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

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

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

/* This code example produces the following output:

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

Sort(dinosaurs, dinosaurSizes)

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

Sort(dinosaurs, dinosaurSizes, rc)

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

Sort(dinosaurs, dinosaurSizes, 3, 3)

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

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

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

        Dim dinosaurs() As String = { _
            "Seismosaurus", _
            "Chasmosaurus", _
            "Coelophysis", _
            "Mamenchisaurus", _
            "Caudipteryx", _
            "Cetiosaurus"  }

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

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

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

    End Sub

End Class

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

Comentarios

Cada clave de la keys Array tiene un elemento correspondiente en el items Array.Each key in the keysArray has a corresponding item in the itemsArray. Cuando se vuelve a ubicar una clave durante la ordenación, el elemento correspondiente en el items Array del mismo modo se cambia de posición.When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Por lo tanto, el items Array se ordenan según la disposición de las claves correspondientes en el keys Array.Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

Si comparer es null, cada clave dentro del intervalo especificado de elementos de la keys Array debe implementar la IComparable<T> interfaz genérica para poder realizar comparaciones con otras claves.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.

Puede ordenar si hay más elementos que las claves, pero no se ordenarán los elementos que no tengan ninguna de las claves correspondientes.You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. No se puede ordenar si hay más teclas que los elementos; al hacerlo se inicia un ArgumentException.You cannot sort if there are more keys than items; doing this throws an ArgumentException.

Si el criterio de ordenación no se ha completado correctamente, los resultados son indefinidos.If the sort is not successfully completed, the results are undefined.

Este método utiliza el algoritmo de ordenación introspectiva (introsort) como sigue:This method uses the introspective sort (introsort) algorithm as follows:

  • Si el tamaño de partición es menos de 16 elementos, utiliza un orden de inserción algoritmo.If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • Si el número de particiones es superior a 2 * registroN, donde N es el intervalo de la matriz de entrada, usa un Heapsort algoritmo.If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • De lo contrario, se usa un Quicksort algoritmo.Otherwise, it uses a Quicksort algorithm.

Esta implementación realiza a una ordenación inestable; es decir, si dos elementos son iguales, es posible que no se conserve su orden.This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. En cambio, una ordenación estable conserva el orden de los elementos que son iguales.In contrast, a stable sort preserves the order of elements that are equal.

Para las matrices que se ordenan mediante el uso de los algoritmos Heapsort y Quicksort, en el peor de los casos, este método es O (n registro n) operación, donde n es 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.

Notas a los autores de las llamadas

El .NET Framework 4 y versiones anteriores usan solo el algoritmo Quicksort.The .NET Framework 4 and earlier versions used only the Quicksort algorithm. QuickSort identifica comparadores no válidos en algunas situaciones en que se inicia la operación de ordenación una IndexOutOfRangeException excepción e inicia un ArgumentException excepción al llamador.Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. A partir de la .NET Framework 4.5.NET Framework 4.5, es posible que las operaciones de ordenación que anteriormente produjo ArgumentException no se iniciará una excepción, ya que los algoritmos de ordenación y heapsort de inserción no detectan un comparador no válido.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. En su mayor parte, esto se aplica a las matrices con menos de 16 elementos.For the most part, this applies to arrays with fewer than 16 elements.

Consulte también:

Se aplica a