Exportar (0) Imprimir
Expandir todo

Array.Sort (Método) (Array)

Ordena los elementos de toda una matriz Array unidimensional utilizando la implementación de IComparable de cada elemento de la matriz Array.

Espacio de nombres: System
Ensamblado: mscorlib (en mscorlib.dll)

public static void Sort (
	Array array
)
public static void Sort (
	Array array
)
public static function Sort (
	array : Array
)

Parámetros

array

Array unidimensional que se va a ordenar.

Tipo de excepciónCondición

ArgumentNullException

array es referencia de objeto null (Nothing en Visual Basic).

RankException

array es multidimensional.

InvalidOperationException

Uno o varios elementos de array no implementan la interfaz IComparable.

Cada elemento de array debe implementar la interfaz IComparable para poder realizar comparaciones con otros elementos de array.

Si la ordenación no se realiza correctamente, los resultados quedarán sin definir.

Este método utiliza el algoritmo QuickSort. Esta implementación realiza una ordenación inestable; es decir, si hay dos elementos iguales, es posible que no se mantenga su orden. En contraste, una ordenación estable conserva el orden de los elementos que son iguales.

Este método suele ser una operación O(n log n), donde n es la propiedad Length de array; aunque en el peor de los casos es una operación O(n^2).

En el siguiente ejemplo se muestra cómo ordenar los valores de una Array mediante el comparador predeterminado y un comparador personalizado que invierte el orden. Conviene señalar que el resultado puede variar en función de CultureInfo actual.

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[] myArr = { "The", "QUICK", "BROWN", "FOX", "jumps", "over", "the", "lazy", "dog" };
      IComparer myComparer = new myReverserClass();
 
      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintIndexAndValues( myArr );
 
      // Sorts a section of the Array using the default comparer.
      Array.Sort( myArr, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintIndexAndValues( myArr );

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

      // Sorts the entire Array using the default comparer.
      Array.Sort( myArr );
      Console.WriteLine( "After sorting the entire Array using the default comparer:" );
      PrintIndexAndValues( myArr );

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

   }
 
   public static void PrintIndexAndValues( String[] myArr )  {
      for ( int i = 0; i < myArr.Length; i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, myArr[i] );
      }
      Console.WriteLine();
   }
}


/* 
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

*/


import System.*;
import System.Collections.*;

public class SamplesArray
{
    public static class MyReverserClass implements IComparer
    {
        // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
        public int Compare(Object x, Object y)
        {
            return (new CaseInsensitiveComparer()).Compare(y, x);
        } //IComparer.Compare
    } //MyReverserClass

    public static void main(String[] args)
    {
        // Creates and initializes a new Array and a new custom comparer.
        String myArr[] = { "The", "QUICK", "BROWN", "FOX", "jumps", "over", 
            "the", "lazy", "dog" };
        IComparer myComparer = new MyReverserClass();

        // Displays the values of the Array.
        Console.WriteLine("The Array initially contains the following values:");
        PrintIndexAndValues(myArr);

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

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

        // Sorts the entire Array using the default comparer.
        Array.Sort(myArr);
        Console.WriteLine("After sorting the entire Array using the default"  
            + " comparer:");
        PrintIndexAndValues(myArr);

        // Sorts the entire Array using the reverse case-insensitive comparer.
        Array.Sort(myArr, myComparer);
        Console.WriteLine("After sorting the entire Array using the reverse "  
            + "case-insensitive comparer:");
        PrintIndexAndValues(myArr);
    } //main

    public static void PrintIndexAndValues(String myArr[])
    {
        for (int i = 0; i < myArr.length; i++) {
            Console.WriteLine("   [{0}] : {1}", System.Convert.ToString(i), 
                myArr.get_Item(i));
        }
        Console.WriteLine();
    } //PrintIndexAndValues
} //SamplesArray
/* 
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

*/

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

.NET Framework

Compatible con: 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 2.0, 1.0

Adiciones de comunidad

AGREGAR
Mostrar:
© 2014 Microsoft