Array.Sort Metodo

Definizione

Ordina gli elementi in una matrice unidimensionale.

Overload

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

Ordina un intervallo di elementi in una coppia di oggetti Array unidimensionali (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'interfaccia IComparer specificata.

Sort(Array, Int32, Int32, IComparer)

Ordina gli elementi in un intervallo di elementi di un oggetto Array unidimensionale usando l'oggetto IComparer specificato.

Sort(Array, Array, Int32, Int32)

Ordina un intervallo di elementi in una coppia di oggetti Array unidimensionali (uno contenente le chiavi e l'altro gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'implementazione di IComparable di ogni chiave.

Sort(Array, Int32, Int32)

Ordina un intervallo di elementi di un oggetto Array unidimensionale usando l'implementazione IComparable di ciascun elemento dell'oggetto Array.

Sort(Array, Array, IComparer)

Ordina una coppia di oggetti Array unidimensionali (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi del primo oggetto Array usando l'interfaccia IComparer specificata.

Sort(Array, Array)

Ordina una coppia di oggetti Array unidimensionali (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi del primo oggetto Array usando l'implementazione di IComparable di ogni chiave.

Sort(Array)

Ordina gli elementi di un'intera Array unidimensionale usando l'implementazione IComparable di ciascun elemento dell'oggetto Array.

Sort(Array, IComparer)

Ordina gli elementi in un oggetto Array unidimensionale usando l'oggetto IComparer specificato.

Sort<T>(T[])

Ordina gli elementi di un intero oggetto Array usando l'implementazione dell'interfaccia generica IComparable<T> di ogni elemento dell'oggetto Array.

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

Ordina gli elementi in un oggetto Array usando l'interfaccia generica IComparer<T> specificata.

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

Ordina gli elementi in un oggetto Array usando l'oggetto Comparison<T> specificato.

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

Ordina un intervallo di elementi di un oggetto Array usando l'implementazione dell'interfaccia generica IComparable<T> di ciascun elemento dell'oggetto Array.

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

Ordina un intervallo di elementi di un oggetto Array usando l'interfaccia generica IComparer<T> specificata.

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

Ordina un intervallo di elementi in una coppia di oggetti Array (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'interfaccia generica IComparer<T> specificata.

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

Ordina una coppia di oggetti Array (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi del primo oggetto Array usando l'implementazione dell'interfaccia generica IComparable<T> di ogni chiave.

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

Ordina una coppia di oggetti Array (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'interfaccia generica IComparer<T> specificata.

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

Ordina un intervallo di elementi in una coppia di oggetti Array (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'implementazione dell'interfaccia generica IComparable<T> di ciascuna chiave.

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

Ordina un intervallo di elementi in una coppia di oggetti Array unidimensionali (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'interfaccia IComparer specificata.

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

Parametri

keys
Array

Oggetto Array unidimensionale che contiene le chiavi da ordinare.

items
Array

Oggetto Array unidimensionale che contiene gli elementi che corrispondono a ogni chiave nell'oggetto keysArray.

-oppure-

null per ordinare solo keysArray.

index
Int32

Indice iniziale dell'intervallo da ordinare.

length
Int32

Numero di elementi nell'intervallo da ordinare.

comparer
IComparer

Implementazione IComparer da usare quando si confrontano gli elementi.

-oppure-

null per usare l'implementazione IComparable di ciascun elemento.

Eccezioni

keys è null.

L'oggetto keysArray è multidimensionale.

-oppure-

L'oggetto itemsArray è multidimensionale.

index è minore del limite inferiore di keys.

-oppure-

length è minore di zero.

items non è null e il limite inferiore di keys non corrisponde al limite inferiore di items.

-oppure-

items non è null e la lunghezza di keys è maggiore della lunghezza di items.

-oppure-

index e length non specificano un intervallo valido in keysArray.

-oppure-

items non è null e index e length non specificano un intervallo valido in itemsArray.

-oppure-

L'implementazione di comparer ha causato un errore durante l'ordinamento. Ad esempio, comparer potrebbe non restituire 0 quando si confronta un elemento con se stesso.

comparer è null, e uno o più elementi in keysArray non implementano l'interfaccia IComparable.

Esempio

Nell'esempio di codice seguente viene illustrato come ordinare due matrici associate in cui la prima matrice contiene le chiavi e la seconda matrice contiene i valori. Gli ordinamenti vengono eseguiti usando l'operatore di confronto predefinito e un operatore di confronto personalizzato che inverte l'ordinamento. Si noti che il risultato può variare a seconda dell'oggetto corrente 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

*/
open System
open System.Collections

type MyReverserClass() = 
    interface IComparer with
        member _.Compare(x, y) =
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let printKeysAndValues (myKeys: string []) (myValues: string []) =
    for i = 0 to myKeys.Length - 1 do
        printfn $"   {myKeys[i],-10}: {myValues[i]}"
    printfn ""

// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()

// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues 

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

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

// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues


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

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub


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

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

   End Sub

End Class


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

Commenti

Ogni chiave in keysArray ha un elemento corrispondente in itemsArray. Quando una chiave viene riposizionata durante l'ordinamento, l'elemento corrispondente in itemsArray viene riposizionato in modo analogo. Pertanto, l'oggetto itemsArray viene ordinato in base alla disposizione delle chiavi corrispondenti in keysArray.

Se comparer è null, ogni chiave all'interno dell'intervallo specificato di elementi in keysArray deve implementare l'interfaccia IComparable per poter eseguire confronti con ogni altra chiave.

È possibile ordinare se sono presenti più elementi rispetto alle chiavi, ma gli elementi che non dispongono di chiavi corrispondenti non verranno ordinati. Non è possibile ordinare se sono presenti più chiavi di elementi; in questo modo viene generata un'eccezione ArgumentException.

Se l'ordinamento non viene completato correttamente, i risultati non sono definiti.

.NET include implementazioni predefinite IComparer elencate nella tabella seguente.

Implementazione Descrizione
System.Collections.CaseInsensitiveComparer Confronta due oggetti, ma esegue un confronto senza distinzione tra maiuscole e minuscole di stringhe.
Comparer.Default Confronta due oggetti usando le convenzioni di ordinamento delle impostazioni cultura correnti.
Comparer.DefaultInvariant Confronta due oggetti usando le convenzioni di ordinamento delle impostazioni cultura invarianti.
Comparer<T>.Default Confronta due oggetti di tipo T utilizzando l'ordinamento predefinito del tipo.

È anche possibile supportare confronti personalizzati fornendo un'istanza della propria IComparer implementazione al comparer parametro . L'esempio esegue questa operazione definendo un'implementazione personalizzata IComparer che inverte l'ordinamento predefinito ed esegue un confronto tra stringhe senza distinzione tra maiuscole e minuscole.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è length.

Note per i chiamanti

.NET Framework 4 e versioni precedenti usavano solo l'algoritmo Quicksort. Quicksort identifica gli strumenti di confronto non validi in alcune situazioni in cui l'operazione di ordinamento genera un'eccezione IndexOutOfRangeException e genera un'eccezione ArgumentException al chiamante. A partire da .NET Framework 4.5, è possibile che le operazioni di ordinamento generate in precedenza ArgumentException non generino un'eccezione, perché gli algoritmi di ordinamento di inserimento e heapsort non rilevano un operatore di confronto non valido. Nella maggior parte dei casi, questo vale per le matrici con meno o uguale a 16 elementi.

Vedi anche

Si applica a

Sort(Array, Int32, Int32, IComparer)

Ordina gli elementi in un intervallo di elementi di un oggetto Array unidimensionale usando l'oggetto IComparer specificato.

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

Parametri

array
Array

Oggetto Array unidimensionale da ordinare.

index
Int32

Indice iniziale dell'intervallo da ordinare.

length
Int32

Numero di elementi nell'intervallo da ordinare.

comparer
IComparer

Implementazione IComparer da usare quando si confrontano gli elementi.

-oppure-

null per usare l'implementazione IComparable di ciascun elemento.

Eccezioni

array è null.

array è multidimensionale.

index è minore del limite inferiore di array.

-oppure-

length è minore di zero.

index e length non specificano un intervallo valido in array.

-oppure-

L'implementazione di comparer ha causato un errore durante l'ordinamento. Ad esempio, comparer potrebbe non restituire 0 quando si confronta un elemento con se stesso.

comparer è null e uno o più elementi in array non implementano l'interfaccia IComparable.

Esempio

Nell'esempio di codice seguente viene illustrato come ordinare i valori in un Array usando il comparer predefinito e un comparer personalizzato che inverte l'ordine di ordinamento. Si noti che il risultato può variare a seconda dell'oggetto corrente 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
open System
open System.Collections

type ReverseComparer() =
    interface IComparer with
        member _.Compare(x, y) =
            // Call CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let displayValues (arr: string []) = 
    for i = 0 to arr.Length - 1 do
        printfn $"   [{i}] : {arr[i]}"
    printfn ""

// Create and initialize a new array.
let words = 
    [| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
       "over"; "the"; "lazy"; "dog" |]

// Instantiate the reverse comparer.
let revComparer = ReverseComparer()

// Display the values of the array.
printfn "The original order of elements in the array:" 
displayValues words

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

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

// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words

// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words

// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
Imports System.Collections

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

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

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

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

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

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

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

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

Commenti

Se comparer è null, ogni elemento all'interno dell'intervallo specificato di elementi in array deve implementare l'interfaccia IComparable per essere in grado di confrontare con ogni altro elemento in array.

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

.NET include implementazioni predefinite IComparer elencate nella tabella seguente.

Implementazione Descrizione
System.Collections.CaseInsensitiveComparer Confronta due oggetti, ma esegue un confronto senza distinzione tra maiuscole e minuscole di stringhe.
Comparer.Default Confronta due oggetti usando le convenzioni di ordinamento delle impostazioni cultura correnti.
Comparer.DefaultInvariant Confronta due oggetti usando le convenzioni di ordinamento delle impostazioni cultura invarianti.
Comparer<T>.Default Confronta due oggetti di tipo usando l'ordinamento predefinito del tipo T .

È anche possibile supportare confronti personalizzati fornendo un'istanza comparer della propria IComparer implementazione al parametro. L'esempio esegue questa operazione definendo una ReverseComparer classe che inverte l'ordine di ordinamento predefinito per le istanze di un tipo ed esegue il confronto tra stringhe senza distinzione tra maiuscole e minuscole.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è length.

Note per i chiamanti

.NET Framework 4 e versioni precedenti usavano solo l'algoritmo Quicksort. Quicksort identifica gli strumenti di confronto non validi in alcune situazioni in cui l'operazione di ordinamento genera un'eccezione IndexOutOfRangeException e genera un'eccezione ArgumentException al chiamante. A partire da .NET Framework 4.5, è possibile che le operazioni di ordinamento generate in precedenza ArgumentException non generino un'eccezione, perché gli algoritmi di ordinamento di inserimento e heapsort non rilevano un operatore di confronto non valido. Nella maggior parte dei casi, questo vale per le matrici con meno o uguale a 16 elementi.

Vedi anche

Si applica a

Sort(Array, Array, Int32, Int32)

Ordina un intervallo di elementi in una coppia di oggetti Array unidimensionali (uno contenente le chiavi e l'altro gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'implementazione di IComparable di ogni chiave.

public:
 static void Sort(Array ^ keys, Array ^ items, int index, int length);
public static void Sort (Array keys, Array items, int index, int length);
public static void Sort (Array keys, Array? items, int index, int length);
static member Sort : Array * Array * int * int -> unit
Public Shared Sub Sort (keys As Array, items As Array, index As Integer, length As Integer)

Parametri

keys
Array

Oggetto Array unidimensionale che contiene le chiavi da ordinare.

items
Array

Oggetto Array unidimensionale che contiene gli elementi che corrispondono a ogni chiave nell'oggetto keysArray.

-oppure-

null per ordinare solo keysArray.

index
Int32

Indice iniziale dell'intervallo da ordinare.

length
Int32

Numero di elementi nell'intervallo da ordinare.

Eccezioni

keys è null.

L'oggetto keysArray è multidimensionale.

-oppure-

L'oggetto itemsArray è multidimensionale.

index è minore del limite inferiore di keys.

-oppure-

length è minore di zero.

items non è null e la lunghezza di keys è maggiore della lunghezza di items.

-oppure-

index e length non specificano un intervallo valido in keysArray.

-oppure-

items non è null e index e length non specificano un intervallo valido in itemsArray.

Uno o più elementi nell'oggetto Array di keys non implementano l'interfaccia IComparable.

Esempio

Nell'esempio di codice seguente viene illustrato come ordinare due matrici associate in cui la prima matrice contiene le chiavi e la seconda matrice contiene i valori. Gli ordinamenti vengono eseguiti usando il comparer predefinito e un comparer personalizzato che inverte l'ordine di ordinamento. Si noti che il risultato può variare a seconda dell'oggetto corrente 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

*/
open System
open System.Collections

type MyReverserClass() = 
    interface IComparer with
        member _.Compare(x, y) =
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let printKeysAndValues (myKeys: string []) (myValues: string []) =
    for i = 0 to myKeys.Length - 1 do
        printfn $"   {myKeys[i],-10}: {myValues[i]}"
    printfn ""

// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()

// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues 

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

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

// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues


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

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub


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

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

   End Sub

End Class


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

Commenti

Ogni chiave nell'oggetto keysArray ha un elemento corrispondente nell'oggetto itemsArray. Quando una chiave viene riposizionata durante l'ordinamento, l'elemento corrispondente nell'oggetto itemsArray viene riposizionato in modo analogo. Pertanto, l'oggetto itemsArray viene ordinato in base alla disposizione delle chiavi corrispondenti in keysArray.

Ogni chiave all'interno dell'intervallo specificato di elementi nell'oggetto keysArray deve implementare l'interfaccia IComparable per essere in grado di confrontarsi con ogni altra chiave.

È possibile ordinare se sono presenti più elementi rispetto alle chiavi, ma gli elementi che non hanno chiavi corrispondenti non verranno ordinati. Non è possibile ordinare se sono presenti più chiavi rispetto agli elementi; in questo modo viene generato un ArgumentExceptionoggetto .

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è length.

Vedi anche

Si applica a

Sort(Array, Int32, Int32)

Ordina un intervallo di elementi di un oggetto Array unidimensionale usando l'implementazione IComparable di ciascun elemento dell'oggetto Array.

public:
 static void Sort(Array ^ array, int index, int length);
public static void Sort (Array array, int index, int length);
static member Sort : Array * int * int -> unit
Public Shared Sub Sort (array As Array, index As Integer, length As Integer)

Parametri

array
Array

Oggetto Array unidimensionale da ordinare.

index
Int32

Indice iniziale dell'intervallo da ordinare.

length
Int32

Numero di elementi nell'intervallo da ordinare.

Eccezioni

array è null.

array è multidimensionale.

index è minore del limite inferiore di array.

-oppure-

length è minore di zero.

index e length non specificano un intervallo valido in array.

Uno o più elementi in array non implementano l'interfaccia IComparable.

Esempio

Nell'esempio di codice seguente viene illustrato come ordinare i valori in un Array usando il comparer predefinito e un comparer personalizzato che inverte l'ordine di ordinamento. Si noti che il risultato può variare a seconda dell'oggetto corrente 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
open System
open System.Collections

type ReverseComparer() =
    interface IComparer with
        member _.Compare(x, y) =
            // Call CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let displayValues (arr: string []) = 
    for i = 0 to arr.Length - 1 do
        printfn $"   [{i}] : {arr[i]}"
    printfn ""

// Create and initialize a new array.
let words = 
    [| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
       "over"; "the"; "lazy"; "dog" |]

// Instantiate the reverse comparer.
let revComparer = ReverseComparer()

// Display the values of the array.
printfn "The original order of elements in the array:" 
displayValues words

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

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

// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words

// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words

// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
Imports System.Collections

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

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

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

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

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

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

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

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

Commenti

Ogni elemento all'interno dell'intervallo specificato di elementi in array deve implementare l'interfaccia IComparable per essere in grado di confrontare con ogni altro elemento in array.

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è length.

Vedi anche

Si applica a

Sort(Array, Array, IComparer)

Ordina una coppia di oggetti Array unidimensionali (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi del primo oggetto Array usando l'interfaccia IComparer specificata.

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

Parametri

keys
Array

Oggetto Array unidimensionale che contiene le chiavi da ordinare.

items
Array

Oggetto Array unidimensionale che contiene gli elementi che corrispondono a ogni chiave nell'oggetto keysArray.

-oppure-

null per ordinare solo keysArray.

comparer
IComparer

Implementazione IComparer da usare quando si confrontano gli elementi.

-oppure-

null per usare l'implementazione IComparable di ciascun elemento.

Eccezioni

keys è null.

L'oggetto keysArray è multidimensionale.

-oppure-

L'oggetto itemsArray è multidimensionale.

items non è null e la lunghezza di keys è maggiore della lunghezza di items.

-oppure-

L'implementazione di comparer ha causato un errore durante l'ordinamento. Ad esempio, comparer potrebbe non restituire 0 quando si confronta un elemento con se stesso.

comparer è null, e uno o più elementi in keysArray non implementano l'interfaccia IComparable.

Esempio

Nell'esempio seguente viene illustrato come ordinare due matrici associate in cui la prima matrice contiene le chiavi e la seconda matrice contiene i valori. Gli ordinamenti vengono eseguiti usando l'operatore di confronto predefinito e un operatore di confronto personalizzato che inverte l'ordinamento. Si noti che il risultato può variare a seconda dell'oggetto corrente 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

*/
open System
open System.Collections

type MyReverserClass() = 
    interface IComparer with
        member _.Compare(x, y) =
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let printKeysAndValues (myKeys: string []) (myValues: string []) =
    for i = 0 to myKeys.Length - 1 do
        printfn $"   {myKeys[i],-10}: {myValues[i]}"
    printfn ""

// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()

// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues 

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

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

// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues


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

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub


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

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

   End Sub

End Class


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

Commenti

Ogni chiave in keysArray ha un elemento corrispondente in itemsArray. Quando una chiave viene riposizionata durante l'ordinamento, l'elemento corrispondente in itemsArray viene riposizionato in modo analogo. Pertanto, l'oggetto itemsArray viene ordinato in base alla disposizione delle chiavi corrispondenti in keysArray.

Se comparer è null, ogni chiave in keysArray deve implementare l'interfaccia IComparable per poter eseguire confronti con ogni altra chiave.

È possibile ordinare se sono presenti più elementi rispetto alle chiavi, ma gli elementi che non dispongono di chiavi corrispondenti non verranno ordinati. Non è possibile ordinare se sono presenti più chiavi di elementi; in questo modo viene generata un'eccezione ArgumentException.

Se l'ordinamento non viene completato correttamente, i risultati non sono definiti.

.NET include implementazioni predefinite IComparer elencate nella tabella seguente.

Implementazione Descrizione
System.Collections.CaseInsensitiveComparer Confronta due oggetti, ma esegue un confronto senza distinzione tra maiuscole e minuscole di stringhe.
Comparer.Default Confronta due oggetti usando le convenzioni di ordinamento delle impostazioni cultura correnti.
Comparer.DefaultInvariant Confronta due oggetti usando le convenzioni di ordinamento delle impostazioni cultura invarianti.
Comparer<T>.Default Confronta due oggetti di tipo T utilizzando l'ordinamento predefinito del tipo.

È anche possibile supportare confronti personalizzati fornendo un'istanza della propria IComparer implementazione al comparer parametro . L'esempio esegue questa operazione definendo un'implementazione IComparer che inverte l'ordinamento predefinito ed esegue un confronto tra stringhe senza distinzione tra maiuscole e minuscole.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log ), dove n è l'oggetto Length di keysn.

Note per i chiamanti

.NET Framework 4 e versioni precedenti usavano solo l'algoritmo Quicksort. Quicksort identifica gli strumenti di confronto non validi in alcune situazioni in cui l'operazione di ordinamento genera un'eccezione IndexOutOfRangeException e genera un'eccezione ArgumentException al chiamante. A partire da .NET Framework 4.5, è possibile che le operazioni di ordinamento generate in precedenza ArgumentException non generino un'eccezione, perché gli algoritmi di ordinamento di inserimento e heapsort non rilevano un operatore di confronto non valido. Nella maggior parte dei casi, questo vale per le matrici con meno o uguale a 16 elementi.

Vedi anche

Si applica a

Sort(Array, Array)

Ordina una coppia di oggetti Array unidimensionali (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi del primo oggetto Array usando l'implementazione di IComparable di ogni chiave.

public:
 static void Sort(Array ^ keys, Array ^ items);
public static void Sort (Array keys, Array items);
public static void Sort (Array keys, Array? items);
static member Sort : Array * Array -> unit
Public Shared Sub Sort (keys As Array, items As Array)

Parametri

keys
Array

Oggetto Array unidimensionale che contiene le chiavi da ordinare.

items
Array

Oggetto Array unidimensionale che contiene gli elementi che corrispondono a ogni chiave nell'oggetto keysArray.

-oppure-

null per ordinare solo keysArray.

Eccezioni

keys è null.

L'oggetto keysArray è multidimensionale.

-oppure-

L'oggetto itemsArray è multidimensionale.

items non è null e la lunghezza di keys è maggiore della lunghezza di items.

Uno o più elementi nell'oggetto Array di keys non implementano l'interfaccia IComparable.

Esempio

Nell'esempio seguente viene illustrato come ordinare due matrici associate in cui la prima matrice contiene le chiavi e la seconda matrice contiene i valori. Gli ordinamenti vengono eseguiti usando l'operatore di confronto predefinito e un operatore di confronto personalizzato che inverte l'ordinamento. Si noti che il risultato può variare a seconda dell'oggetto corrente 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

*/
open System
open System.Collections

type MyReverserClass() = 
    interface IComparer with
        member _.Compare(x, y) =
            // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let printKeysAndValues (myKeys: string []) (myValues: string []) =
    for i = 0 to myKeys.Length - 1 do
        printfn $"   {myKeys[i],-10}: {myValues[i]}"
    printfn ""

// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()

// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues 

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

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

// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues

// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues


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

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

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

   End Class


   Public Shared Sub Main()

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

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

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

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

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

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

   End Sub


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

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

   End Sub

End Class


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

Commenti

Ogni chiave in keysArray ha un elemento corrispondente in itemsArray. Quando una chiave viene riposizionata durante l'ordinamento, l'elemento corrispondente in itemsArray viene riposizionato in modo analogo. Pertanto, l'oggetto itemsArray viene ordinato in base alla disposizione delle chiavi corrispondenti in keysArray.

Ogni chiave in keysArray deve implementare l'interfaccia IComparable in modo che sia in grado di eseguire confronti con ogni altra chiave.

È possibile ordinare se sono presenti più elementi rispetto alle chiavi, ma gli elementi che non dispongono di chiavi corrispondenti non verranno ordinati. Non è possibile ordinare se sono presenti più chiavi di elementi; in questo modo viene generata un'eccezione ArgumentException.

Se l'ordinamento non viene completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log ), dove n è l'oggetto Length di keysn.

Vedi anche

Si applica a

Sort(Array)

Ordina gli elementi di un'intera Array unidimensionale usando l'implementazione IComparable di ciascun elemento dell'oggetto Array.

public:
 static void Sort(Array ^ array);
public static void Sort (Array array);
static member Sort : Array -> unit
Public Shared Sub Sort (array As Array)

Parametri

array
Array

Oggetto Array unidimensionale da ordinare.

Eccezioni

array è null.

array è multidimensionale.

Uno o più elementi in array non implementano l'interfaccia IComparable.

Esempio

Nell'esempio di codice seguente viene illustrato come ordinare i valori in un Array oggetto utilizzando l'operatore di confronto predefinito e un operatore di confronto personalizzato che inverte l'ordinamento. Si noti che il risultato può variare a seconda dell'oggetto corrente 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
open System
open System.Collections

type ReverseComparer() =
    interface IComparer with
        member _.Compare(x, y) =
            // Call CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let displayValues (arr: string []) = 
    for i = 0 to arr.Length - 1 do
        printfn $"   [{i}] : {arr[i]}"
    printfn ""

// Create and initialize a new array.
let words = 
    [| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
       "over"; "the"; "lazy"; "dog" |]

// Instantiate the reverse comparer.
let revComparer = ReverseComparer()

// Display the values of the array.
printfn "The original order of elements in the array:" 
displayValues words

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

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

// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words

// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words

// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
Imports System.Collections

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

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

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

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

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

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

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

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

Commenti

Ogni elemento di array deve implementare l'interfaccia IComparable per poter eseguire confronti con ogni altro elemento in array.

Se l'ordinamento non viene completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log ), dove n è l'oggetto Length di arrayn.

Vedi anche

Si applica a

Sort(Array, IComparer)

Ordina gli elementi in un oggetto Array unidimensionale usando l'oggetto IComparer specificato.

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

Parametri

array
Array

Matrice unidimensionale da ordinare.

comparer
IComparer

Implementazione da usare per il confronto degli elementi.

-oppure-

null per usare l'implementazione IComparable di ciascun elemento.

Eccezioni

array è null.

array è multidimensionale.

comparer è null e uno o più elementi in array non implementano l'interfaccia IComparable.

L'implementazione di comparer ha causato un errore durante l'ordinamento. Ad esempio, comparer potrebbe non restituire 0 quando si confronta un elemento con se stesso.

Esempio

Nell'esempio seguente vengono ordinati i valori in una matrice di stringhe usando l'operatore di confronto predefinito. Definisce anche un'implementazione personalizzata denominata IComparerReverseComparer che inverte l'ordinamento predefinito di un oggetto eseguendo un confronto tra stringhe senza distinzione tra maiuscole e minuscole. Si noti che l'output può variare a seconda delle impostazioni cultura correnti.

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
open System
open System.Collections

type ReverseComparer() =
    interface IComparer with
        member _.Compare(x, y) =
            // Call CaseInsensitiveComparer.Compare with the parameters reversed.
            CaseInsensitiveComparer().Compare(y, x)

let displayValues (arr: string []) = 
    for i = 0 to arr.Length - 1 do
        printfn $"   [{i}] : {arr[i]}"
    printfn ""

// Create and initialize a new array.
let words = 
    [| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
       "over"; "the"; "lazy"; "dog" |]

// Instantiate the reverse comparer.
let revComparer = ReverseComparer()

// Display the values of the array.
printfn "The original order of elements in the array:" 
displayValues words

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

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

// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words

// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words

// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN
Imports System.Collections

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

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

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

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

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

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

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

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

Commenti

Se comparer è null, ogni elemento di deve implementare l'interfaccia IComparable per essere in grado di array confrontare con ogni altro elemento in array.

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è l'oggetto Length di array.

.NET include implementazioni predefinite IComparer elencate nella tabella seguente.

Implementazione Descrizione
System.Collections.CaseInsensitiveComparer Confronta due oggetti, ma esegue un confronto senza distinzione tra maiuscole e minuscole di stringhe.
Comparer.Default Confronta due oggetti usando le convenzioni di ordinamento delle impostazioni cultura correnti.
Comparer.DefaultInvariant Confronta due oggetti usando le convenzioni di ordinamento delle impostazioni cultura invarianti.
Comparer<T>.Default Confronta due oggetti di tipo usando l'ordinamento predefinito del tipo T .

È anche possibile supportare confronti personalizzati fornendo un'istanza comparer della propria IComparer implementazione al parametro. L'esempio esegue questa operazione definendo una ReverseComparer classe che inverte l'ordine di ordinamento predefinito per le istanze di un tipo ed esegue il confronto tra stringhe senza distinzione tra maiuscole e minuscole.

Note per i chiamanti

.NET Framework 4 e versioni precedenti usavano solo l'algoritmo Quicksort. Quicksort identifica gli strumenti di confronto non validi in alcune situazioni in cui l'operazione di ordinamento genera un'eccezione IndexOutOfRangeException e genera un'eccezione ArgumentException al chiamante. A partire da .NET Framework 4.5, è possibile che le operazioni di ordinamento generate in precedenza ArgumentException non generino un'eccezione, perché gli algoritmi di ordinamento di inserimento e heapsort non rilevano un operatore di confronto non valido. Nella maggior parte dei casi, questo vale per le matrici con meno o uguale a 16 elementi.

Vedi anche

Si applica a

Sort<T>(T[])

Ordina gli elementi di un intero oggetto Array usando l'implementazione dell'interfaccia generica IComparable<T> di ogni elemento dell'oggetto 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())

Parametri di tipo

T

Tipo degli elementi della matrice.

Parametri

array
T[]

Oggetto Array unidimensionale e in base zero da ordinare.

Eccezioni

array è null.

Uno o più elementi in array non implementano l'interfaccia generica IComparable<T>.

Esempio

Nell'esempio di codice seguente viene illustrato l'overload del metodo generico e l'overload Sort<T>(T[]) del BinarySearch<T>(T[], T) metodo generico. Viene creata una matrice di stringhe, in nessun ordine specifico.

La matrice viene visualizzata, ordinata e visualizzata di nuovo.

Nota

Le chiamate ai Sort metodi generici e BinarySearch non sembrano diverse dalle chiamate alle loro controparti nongeneriche, perché Visual Basic, C#e C++ deducono il tipo del parametro di tipo generico dal tipo del primo argomento. Se si usa il Ildasm.exe (IL Disassembler) per esaminare il linguaggio intermedio Microsoft (MSIL), è possibile notare che i metodi generici vengono chiamati.

L'overload BinarySearch<T>(T[], T) del metodo generico viene quindi usato per cercare due stringhe, una che non è nella matrice e una che è. La matrice e il valore restituito del metodo vengono passati al ShowWhere metodo generico, che visualizza il valore dell'indice BinarySearch se la stringa viene trovata e in caso contrario gli elementi della stringa di ricerca rientrano tra se fosse presente nella matrice. L'indice è negativo se la stringa non è n la matrice, quindi il ShowWhere metodo accetta il complemento bit per bit (l'operatore ~ in C# e Visual C++, Xor -1 in Visual Basic) per ottenere l'indice del primo elemento nell'elenco più grande della stringa di ricerca.

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.
 */
open System

let showWhere (array: 'a []) index =
    if index < 0 then
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        let index = ~~~index

        printf "Not found. Sorts between: "

        if index = 0 then
            printf "beginning of array and "
        else
            printf $"{array[index - 1]} and "

        if index = array.Length then
            printfn "end of array."
        else
            printfn $"{array[index]}."
    else
        printfn $"Found at index {index}."

let dinosaurs =
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Tyrannosaurus"
       "Mamenchisaurus"
       "Deinonychus"
       "Edmontosaurus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nSort"
Array.Sort dinosaurs

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nBinarySearch for 'Coelophysis':"
let index = Array.BinarySearch(dinosaurs, "Coelophysis")
showWhere dinosaurs index

printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus")
|> showWhere dinosaurs


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

Public Class Example

    Public Shared Sub Main()

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

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

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

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

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

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

    End Sub

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

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

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

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

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

    End Sub

End Class

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

Commenti

Ogni elemento di deve implementare l'interfaccia IComparable<T> generica per essere in grado di array confrontare con ogni altro elemento in array.

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è l'oggetto Length di array.

Vedi anche

Si applica a

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

Ordina gli elementi in un oggetto Array usando l'interfaccia generica IComparer<T> specificata.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array, System::Collections::Generic::IComparer<T> ^ comparer);
public static void Sort<T> (T[] array, System.Collections.Generic.IComparer<T> comparer);
public static void Sort<T> (T[] array, System.Collections.Generic.IComparer<T>? comparer);
static member Sort : 'T[] * System.Collections.Generic.IComparer<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), comparer As IComparer(Of T))

Parametri di tipo

T

Tipo degli elementi della matrice.

Parametri

array
T[]

Ordinamento uno-dimensionale, zero-base Array da ordinare.

comparer
IComparer<T>

Implementazione dell'interfaccia generica IComparer<T> da usare per il confronto fra gli elementi oppure null per usare l'implementazione dell'interfaccia generica IComparable<T> di ciascun elemento.

Eccezioni

array è null.

comparer è null e uno o più elementi in array non implementano l'interfaccia generica di IComparable<T>.

L'implementazione di comparer ha causato un errore durante l'ordinamento. Ad esempio, comparer potrebbe non restituire 0 quando si confronta un elemento con se stesso.

Esempio

Nell'esempio di codice seguente viene illustrato l'overload del metodo generico e l'overload Sort<T>(T[], IComparer<T>) del BinarySearch<T>(T[], T, IComparer<T>) metodo generico.

L'esempio di codice definisce un comparer alternativo per le stringhe, denominato ReverseCompare, che implementa l'interfaccia IComparer<string> generica (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++). Il comparer chiama il metodo, ripristinando l'ordine CompareTo(String) dei comparandi in modo che le stringhe ordinano high-to-low anziché low-to-high.

La matrice viene visualizzata, ordinata e visualizzata di nuovo. Per usare il BinarySearch metodo, è necessario ordinare le matrici.

Nota

Le chiamate ai Sort<T>(T[], IComparer<T>) metodi generici e BinarySearch<T>(T[], T, IComparer<T>) non sembrano diverse dalle chiamate alle loro controparti nongeneriche, perché Visual Basic, C#e C++ deducono il tipo del parametro di tipo generico dal tipo del primo argomento. Se si usa il Ildasm.exe (IL Disassembler) per esaminare il linguaggio intermedio Microsoft (MSIL), è possibile notare che i metodi generici vengono chiamati.

L'overload BinarySearch<T>(T[], T, IComparer<T>) del metodo generico viene quindi usato per cercare due stringhe, una che non è nella matrice e una che è. La matrice e il valore restituito del metodo vengono passati al ShowWhere metodo generico, che visualizza il valore dell'indice BinarySearch<T>(T[], T, IComparer<T>) se la stringa viene trovata e in caso contrario gli elementi della stringa di ricerca rientrano tra se fosse presente nella matrice. L'indice è negativo se la stringa non è n la matrice, quindi il ShowWhere metodo accetta il complemento bit per bit (l'operatore ~ in C# e Visual C++, Xor -1 in Visual Basic) per ottenere l'indice del primo elemento nell'elenco più grande della stringa di ricerca.

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.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            // Compare y and x in reverse order.
            y.CompareTo x

let showWhere (array: 'a []) index =
    if index < 0 then
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        let index = ~~~index

        printf "Not found. Sorts between: "

        if index = 0 then
            printf "beginning of array and "
        else
            printf $"{array[index - 1]} and "

        if index = array.Length then
            printfn "end of array."
        else
            printfn $"{array[index]}."
    else
        printfn $"Found at index {index}."

let dinosaurs =
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Tyrannosaurus"
       "Mamenchisaurus"
       "Deinonychus"
       "Edmontosaurus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

let rc = ReverseComparer()

printfn "\nSort"
Array.Sort(dinosaurs, rc)

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nBinarySearch for 'Coelophysis':"
Array.BinarySearch(dinosaurs, "Coelophysis", rc)
|> showWhere dinosaurs

printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
|> showWhere dinosaurs


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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

    End Sub

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

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

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

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

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

    End Sub

End Class

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

Commenti

Se comparer è null, ogni elemento di deve implementare l'interfaccia IComparable<T> generica per essere in grado di array confrontarsi con ogni altro elemento in array.

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è l'oggetto Length di array.

Note per i chiamanti

.NET Framework 4 e versioni precedenti usavano solo l'algoritmo Quicksort. Quicksort identifica i comparer non validi in alcune situazioni in cui l'operazione di ordinamento genera un'eccezione e genera un'eccezione IndexOutOfRangeExceptionArgumentException al chiamante. A partire da .NET Framework 4.5, è possibile che le operazioni di ordinamento che in precedenza hanno generato ArgumentException non genereranno un'eccezione, perché gli algoritmi di inserimento e heapsort non rilevano un comparer non valido. Per la maggior parte, questo vale per le matrici con meno di o uguale a 16 elementi.

Vedi anche

Si applica a

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

Ordina gli elementi in un oggetto Array usando l'oggetto Comparison<T> specificato.

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

Parametri di tipo

T

Tipo degli elementi della matrice.

Parametri

array
T[]

Oggetto Array unidimensionale e in base zero da ordinare.

comparison
Comparison<T>

Oggetto Comparison<T> da usare quando si confrontano gli elementi.

Eccezioni

array è null.

-oppure-

comparison è null.

L'implementazione di comparison ha causato un errore durante l'ordinamento. Ad esempio, comparison potrebbe non restituire 0 quando si confronta un elemento con se stesso.

Esempio

Nell'esempio di codice seguente viene illustrato l'overload del Sort(Comparison<T>) metodo.

L'esempio di codice definisce un metodo di confronto alternativo per le stringhe, denominato CompareDinosByLength. Questo metodo funziona come segue: prima, i comparand vengono testatinull e un riferimento Null viene considerato minore di un valore null. In secondo luogo, le lunghezze delle stringhe vengono confrontate e la stringa più lunga viene considerata maggiore. In terzo luogo, se le lunghezze sono uguali, viene usato il confronto di stringhe normali.

Una matrice di stringhe viene creata e popolata con quattro stringhe, in nessun ordine specifico. L'elenco include anche una stringa vuota e un riferimento Null. L'elenco viene visualizzato, ordinato usando un Comparison<T> delegato generico che rappresenta il CompareDinosByLength metodo e visualizzato di nuovo.

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"
 */
open System

let compareDinosByLength (x: string) (y: string) =
    match x with
    // If x is null and y is null, they're equal.
    | null when isNull y -> 0 
    // If x is null and y is not null, y is greater.
    | null -> -1
    // If x is not null and y is null, x is greater.
    | _ when isNull y -> 1    
    // If x is not null and y is not null, compare the lengths of the two strings.
    | _ ->
        let retval = x.Length.CompareTo y.Length
        if retval <> 0 then
            // If the strings are not of equal length, the longer string is greater.
            retval
        else
            // If the strings are of equal length, sort them with ordinary string comparison.
            x.CompareTo y

let display arr =
    printfn ""
    for s in arr do
        if isNull s then
            printfn "(null)"
        else
            printfn $"\"{s}\""

let dinosaurs =
    [| "Pachycephalosaurus"
       "Amargasaurus"
       ""
       null
       "Mamenchisaurus"
       "Deinonychus" |]
       
display dinosaurs

printfn "\nSort with generic Comparison<string> delegate:"
Array.Sort(dinosaurs, compareDinosByLength)
display dinosaurs

// This code example produces the following output:
//
//    "Pachycephalosaurus"
//    "Amargasaurus"
//    ""
//    (null)
//    "Mamenchisaurus"
//    "Deinonychus"
//    
//    Sort with generic Comparison<string> delegate:
//    
//    (null)
//    ""
//    "Deinonychus"
//    "Amargasaurus"
//    "Mamenchisaurus"
//    "Pachycephalosaurus"
//
Imports System.Collections.Generic

Public Class Example

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

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

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

    End Function

    Public Shared Sub Main()

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

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

    End Sub

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

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

Commenti

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è l'oggetto Length di array.

Note per i chiamanti

.NET Framework 4 e versioni precedenti usavano solo l'algoritmo Quicksort. Quicksort identifica i comparer non validi in alcune situazioni in cui l'operazione di ordinamento genera un'eccezione e genera un'eccezione IndexOutOfRangeExceptionArgumentException al chiamante. A partire da .NET Framework 4.5, è possibile che le operazioni di ordinamento che in precedenza hanno generato ArgumentException non genereranno un'eccezione, perché gli algoritmi di inserimento e heapsort non rilevano un comparer non valido. Per la maggior parte, questa operazione si applica alle matrici con meno o uguali a 6 elementi.

Vedi anche

Si applica a

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

Ordina un intervallo di elementi di un oggetto Array usando l'implementazione dell'interfaccia generica IComparable<T> di ciascun elemento dell'oggetto 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)

Parametri di tipo

T

Tipo degli elementi della matrice.

Parametri

array
T[]

Oggetto Array unidimensionale e in base zero da ordinare.

index
Int32

Indice iniziale dell'intervallo da ordinare.

length
Int32

Numero di elementi nell'intervallo da ordinare.

Eccezioni

array è null.

index è minore del limite inferiore di array.

-oppure-

length è minore di zero.

index e length non specificano un intervallo valido in array.

Uno o più elementi in array non implementano l'interfaccia generica IComparable<T>.

Esempio

Nell'esempio di codice seguente viene illustrato l'overload del metodo generico e l'overload Sort<T>(T[], Int32, Int32)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) del metodo generico per ordinare un intervallo in una matrice.

L'esempio di codice definisce un comparer alternativo per le stringhe, denominato ReverseCompare, che implementa l'interfaccia IComparer<string> generica (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++). Il comparer chiama il metodo, ripristinando l'ordine CompareTo(String) dei comparandi in modo che le stringhe ordinano high-to-low anziché low-to-high.

L'esempio di codice crea e visualizza una matrice di nomi di dinosauro, costituiti da tre erbivori seguiti da tre carnivori (tyrannosauridi, per essere precisi). L'overload Sort<T>(T[], Int32, Int32) del metodo generico viene usato per ordinare gli ultimi tre elementi della matrice, quindi visualizzati. L'overload Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) del metodo generico viene usato con ReverseCompare per ordinare gli ultimi tre elementi in ordine inverso. I dinosauri completamente confusi vengono visualizzati di nuovo.

Nota

Le chiamate ai Sort<T>(T[], IComparer<T>) metodi generici e BinarySearch<T>(T[], T, IComparer<T>) non sembrano diverse dalle chiamate alle loro controparti nongeneriche, perché Visual Basic, C#e C++ deducono il tipo del parametro di tipo generico dal tipo del primo argomento. Se si usa il Ildasm.exe (IL Disassembler) per esaminare il linguaggio intermedio Microsoft (MSIL), è possibile notare che i metodi generici vengono chiamati.

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
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface  IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs = 
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Tarbosaurus"
       "Tyrannosaurus"
       "Albertasaurus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nSort(dinosaurs, 3, 3)"
Array.Sort(dinosaurs, 3, 3)

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

let rc = ReverseComparer()

printfn "\nSort(dinosaurs, 3, 3, rc)"
Array.Sort(dinosaurs, 3, 3, rc)

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"


// This code example produces the following output:
//
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Tarbosaurus
//    Tyrannosaurus
//    Albertasaurus
//    
//    Sort(dinosaurs, 3, 3)
//    
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Albertasaurus
//    Tarbosaurus
//    Tyrannosaurus
//    
//    Sort(dinosaurs, 3, 3, rc)
//    
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Tyrannosaurus
//    Tarbosaurus
//    Albertasaurus
Imports System.Collections.Generic

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

    End Sub

End Class

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

Commenti

Ogni elemento all'interno dell'intervallo specificato di elementi in array deve implementare l'interfaccia IComparable<T> generica per essere in grado di confrontare con ogni altro elemento in array.

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è length.

Vedi anche

Si applica a

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

Ordina un intervallo di elementi di un oggetto Array usando l'interfaccia generica IComparer<T> specificata.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array, int index, int length, System::Collections::Generic::IComparer<T> ^ comparer);
public static void Sort<T> (T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer);
public static void Sort<T> (T[] array, int index, int length, System.Collections.Generic.IComparer<T>? comparer);
static member Sort : 'T[] * int * int * System.Collections.Generic.IComparer<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), index As Integer, length As Integer, comparer As IComparer(Of T))

Parametri di tipo

T

Tipo degli elementi della matrice.

Parametri

array
T[]

Oggetto Array unidimensionale e in base zero da ordinare.

index
Int32

Indice iniziale dell'intervallo da ordinare.

length
Int32

Numero di elementi nell'intervallo da ordinare.

comparer
IComparer<T>

Implementazione dell'interfaccia generica IComparer<T> da usare per il confronto fra gli elementi oppure null per usare l'implementazione dell'interfaccia generica IComparable<T> di ciascun elemento.

Eccezioni

array è null.

index è minore del limite inferiore di array.

-oppure-

length è minore di zero.

index e length non specificano un intervallo valido in array.

-oppure-

L'implementazione di comparer ha causato un errore durante l'ordinamento. Ad esempio, comparer potrebbe non restituire 0 quando si confronta un elemento con se stesso.

comparer è null e uno o più elementi in array non implementano l'interfaccia generica di IComparable<T>.

Esempio

Nell'esempio di codice seguente viene illustrato l'overload del metodo generico e l'overload Sort<T>(T[], Int32, Int32)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) del metodo generico per ordinare un intervallo in una matrice.

L'esempio di codice definisce un comparer alternativo per le stringhe, denominato ReverseCompare, che implementa l'interfaccia IComparer<string> generica (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++). Il comparer chiama il metodo, ripristinando l'ordine CompareTo(String) dei comparandi in modo che le stringhe ordinano high-to-low anziché low-to-high.

L'esempio di codice crea e visualizza una matrice di nomi di dinosauro, costituiti da tre erbivori seguiti da tre carnivori (tyrannosauridi, per essere precisi). L'overload Sort<T>(T[], Int32, Int32) del metodo generico viene usato per ordinare gli ultimi tre elementi della matrice, quindi visualizzati. L'overload Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) del metodo generico viene usato con ReverseCompare per ordinare gli ultimi tre elementi in ordine inverso. I dinosauri completamente confusi vengono visualizzati di nuovo.

Nota

Le chiamate ai Sort<T>(T[], IComparer<T>) metodi generici e BinarySearch<T>(T[], T, IComparer<T>) non sembrano diverse dalle chiamate alle loro controparti nongeneriche, perché Visual Basic, C#e C++ deducono il tipo del parametro di tipo generico dal tipo del primo argomento. Se si usa il Ildasm.exe (IL Disassembler) per esaminare il linguaggio intermedio Microsoft (MSIL), è possibile notare che i metodi generici vengono chiamati.

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
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface  IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs = 
    [| "Pachycephalosaurus"
       "Amargasaurus"
       "Mamenchisaurus"
       "Tarbosaurus"
       "Tyrannosaurus"
       "Albertasaurus" |]

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

printfn "\nSort(dinosaurs, 3, 3)"
Array.Sort(dinosaurs, 3, 3)

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"

let rc = ReverseComparer()

printfn "\nSort(dinosaurs, 3, 3, rc)"
Array.Sort(dinosaurs, 3, 3, rc)

printfn ""
for dino in dinosaurs do
    printfn $"{dino}"


// This code example produces the following output:
//
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Tarbosaurus
//    Tyrannosaurus
//    Albertasaurus
//    
//    Sort(dinosaurs, 3, 3)
//    
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Albertasaurus
//    Tarbosaurus
//    Tyrannosaurus
//    
//    Sort(dinosaurs, 3, 3, rc)
//    
//    Pachycephalosaurus
//    Amargasaurus
//    Mamenchisaurus
//    Tyrannosaurus
//    Tarbosaurus
//    Albertasaurus
Imports System.Collections.Generic

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

    End Sub

End Class

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

Commenti

Se comparer è null, ogni elemento all'interno dell'intervallo specificato di elementi in array deve implementare l'interfaccia IComparable<T> generica per essere in grado di confrontarsi con ogni altro elemento in array.

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è length.

Note per i chiamanti

.NET Framework 4 e versioni precedenti usavano solo l'algoritmo Quicksort. Quicksort identifica i comparer non validi in alcune situazioni in cui l'operazione di ordinamento genera un'eccezione e genera un'eccezione IndexOutOfRangeExceptionArgumentException al chiamante. A partire da .NET Framework 4.5, è possibile che le operazioni di ordinamento che in precedenza hanno generato ArgumentException non genereranno un'eccezione, perché gli algoritmi di inserimento e heapsort non rilevano un comparer non valido. Per la maggior parte, questo vale per le matrici con meno di o uguale a 16 elementi.

Vedi anche

Si applica a

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

Ordina un intervallo di elementi in una coppia di oggetti Array (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'interfaccia generica IComparer<T> specificata.

public:
generic <typename TKey, typename TValue>
 static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items, int index, int length, System::Collections::Generic::IComparer<TKey> ^ comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items, int index, int length, System.Collections.Generic.IComparer<TKey>? comparer);
static member Sort : 'Key[] * 'Value[] * int * int * System.Collections.Generic.IComparer<'Key> -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue(), index As Integer, length As Integer, comparer As IComparer(Of TKey))

Parametri di tipo

TKey

Tipo degli elementi della matrice delle chiavi.

TValue

Tipo degli elementi della matrice degli elementi.

Parametri

keys
TKey[]

Oggetto Array unidimensionale in base zero che contiene le chiavi da ordinare.

items
TValue[]

Oggetto unidimensionale in base zero Array che contiene gli elementi che corrispondono alle chiavi in keys oppure null per ordinare solo keys.

index
Int32

Indice iniziale dell'intervallo da ordinare.

length
Int32

Numero di elementi nell'intervallo da ordinare.

comparer
IComparer<TKey>

Implementazione dell'interfaccia generica IComparer<T> da usare per il confronto fra gli elementi oppure null per usare l'implementazione dell'interfaccia generica IComparable<T> di ciascun elemento.

Eccezioni

keys è null.

index è minore del limite inferiore di keys.

-oppure-

length è minore di zero.

items non è null e il limite inferiore di keys non corrisponde al limite inferiore di items.

-oppure-

items non è null e la lunghezza di keys è maggiore della lunghezza di items.

-oppure-

index e length non specificano un intervallo valido in keysArray.

-oppure-

items non è null e index e length non specificano un intervallo valido in itemsArray.

-oppure-

L'implementazione di comparer ha causato un errore durante l'ordinamento. Ad esempio, comparer potrebbe non restituire 0 quando si confronta un elemento con se stesso.

comparer è null, e uno o più elementi in keysArray non implementano l'interfaccia generica IComparable<T>.

Esempio

Nell'esempio di codice seguente vengono illustrati gli overload dei Sort<TKey,TValue>(TKey[], TValue[])metodi , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)e Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generici per ordinare coppie di matrici che rappresentano chiavi e valori.

L'esempio di codice definisce un comparer alternativo per le stringhe, denominato ReverseCompare, che implementa l'interfaccia IComparer<string>generica (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++). Il comparer chiama il metodo, ripristinando l'ordine CompareTo(String) dei comparandi in modo che le stringhe ordinano high-to-low anziché low-to-high.

L'esempio di codice crea e visualizza una matrice di nomi di dinosauro (le chiavi) e una matrice di interi che rappresentano la lunghezza massima di ogni dinosauro in metri (i valori). Le matrici vengono quindi ordinate e visualizzate più volte:

Nota

Le chiamate ai metodi generici non sembrano diverse dalle chiamate alle loro controparti nongeneriche, perché Visual Basic, C#e C++ inferiscono il tipo del parametro di tipo generico dal tipo dei primi due argomenti. Se si usa il Ildasm.exe (IL Disassembler) per esaminare il linguaggio intermedio Microsoft (MSIL), è possibile notare che i metodi generici vengono chiamati.

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.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs =
    [| "Seismosaurus"
       "Chasmosaurus"
       "Coelophysis"
       "Mamenchisaurus"
       "Caudipteryx"
       "Cetiosaurus" |]

let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes)"
Array.Sort(dinosaurs, dinosaurSizes)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

let rc = ReverseComparer()

printfn "\nSort(dinosaurs, dinosaurSizes, rc)"
Array.Sort(dinosaurs, dinosaurSizes, rc)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

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

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

    End Sub

End Class

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

Commenti

Ogni chiave nell'oggetto keysArray ha un elemento corrispondente nell'oggetto itemsArray. Quando una chiave viene riposizionata durante l'ordinamento, l'elemento corrispondente nell'oggetto itemsArray viene riposizionato in modo analogo. Pertanto, l'oggetto itemsArray viene ordinato in base alla disposizione delle chiavi corrispondenti in keysArray.

Se comparer è null, ogni chiave all'interno dell'intervallo specificato di elementi nell'oggetto keysArray deve implementare l'interfaccia IComparable<T> generica per essere in grado di confrontare con ogni altra chiave.

È possibile ordinare se sono presenti più elementi rispetto alle chiavi, ma gli elementi che non hanno chiavi corrispondenti non verranno ordinati. Non è possibile ordinare se sono presenti più chiavi rispetto agli elementi; in questo modo viene generato un ArgumentExceptionoggetto .

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è length.

Note per i chiamanti

.NET Framework 4 e versioni precedenti usavano solo l'algoritmo Quicksort. Quicksort identifica i comparer non validi in alcune situazioni in cui l'operazione di ordinamento genera un'eccezione e genera un'eccezione IndexOutOfRangeExceptionArgumentException al chiamante. A partire da .NET Framework 4.5, è possibile che le operazioni di ordinamento che in precedenza hanno generato ArgumentException non genereranno un'eccezione, perché gli algoritmi di inserimento e heapsort non rilevano un comparer non valido. Per la maggior parte, questo vale per le matrici con meno di o uguale a 16 elementi.

Vedi anche

Si applica a

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

Ordina una coppia di oggetti Array (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi del primo oggetto Array usando l'implementazione dell'interfaccia generica IComparable<T> di ogni chiave.

public:
generic <typename TKey, typename TValue>
 static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items);
static member Sort : 'Key[] * 'Value[] -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue())

Parametri di tipo

TKey

Tipo degli elementi della matrice delle chiavi.

TValue

Tipo degli elementi della matrice degli elementi.

Parametri

keys
TKey[]

Oggetto Array unidimensionale in base zero che contiene le chiavi da ordinare.

items
TValue[]

Oggetto unidimensionale in base zero Array che contiene gli elementi che corrispondono alle chiavi in keys oppure null per ordinare solo keys.

Eccezioni

keys è null.

items non è null e il limite inferiore di keys non corrisponde al limite inferiore di items.

-oppure-

items non è null e la lunghezza di keys è maggiore della lunghezza di items.

Uno o più elementi in keysArray non implementano l'interfaccia generica IComparable<T>.

Esempio

Nell'esempio di codice seguente vengono illustrati gli overload dei Sort<TKey,TValue>(TKey[], TValue[])metodi , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)e Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generici per ordinare coppie di matrici che rappresentano chiavi e valori.

L'esempio di codice definisce un comparer alternativo per le stringhe, denominato ReverseCompare, che implementa l'interfaccia IComparer<string> generica (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++). Il comparer chiama il metodo, ripristinando l'ordine CompareTo(String) dei comparandi in modo che le stringhe ordinano high-to-low anziché low-to-high.

L'esempio di codice crea e visualizza una matrice di nomi di dinosauro (le chiavi) e una matrice di interi che rappresentano la lunghezza massima di ogni dinosauro in metri (i valori). Le matrici vengono quindi ordinate e visualizzate più volte:

Nota

Le chiamate ai metodi generici non sembrano diverse dalle chiamate alle loro controparti nongeneriche, perché Visual Basic, C#e C++ inferiscono il tipo del parametro di tipo generico dal tipo dei primi due argomenti. Se si usa il Ildasm.exe (IL Disassembler) per esaminare il linguaggio intermedio Microsoft (MSIL), è possibile notare che i metodi generici vengono chiamati.

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.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs =
    [| "Seismosaurus"
       "Chasmosaurus"
       "Coelophysis"
       "Mamenchisaurus"
       "Caudipteryx"
       "Cetiosaurus" |]

let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes)"
Array.Sort(dinosaurs, dinosaurSizes)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

let rc = ReverseComparer()

printfn "\nSort(dinosaurs, dinosaurSizes, rc)"
Array.Sort(dinosaurs, dinosaurSizes, rc)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

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

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

    End Sub

End Class

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

Commenti

Ogni chiave nell'oggetto keysArray ha un elemento corrispondente nell'oggetto itemsArray. Quando una chiave viene riposizionata durante l'ordinamento, l'elemento corrispondente nell'oggetto itemsArray viene riposizionato in modo analogo. Pertanto, l'oggetto itemsArray viene ordinato in base alla disposizione delle chiavi corrispondenti in keysArray.

Ogni chiave nell'oggetto keysArray deve implementare l'interfaccia IComparable<T> generica per essere in grado di confrontarsi con ogni altra chiave.

È possibile ordinare se sono presenti più elementi rispetto alle chiavi, ma gli elementi che non hanno chiavi corrispondenti non verranno ordinati. Non è possibile ordinare se sono presenti più chiavi rispetto agli elementi; in questo modo viene generato un ArgumentExceptionoggetto .

Se l'ordinamento non è stato completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è l'oggetto Length di array.

Vedi anche

Si applica a

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

Ordina una coppia di oggetti Array (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'interfaccia generica IComparer<T> specificata.

public:
generic <typename TKey, typename TValue>
 static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items, System::Collections::Generic::IComparer<TKey> ^ comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items, System.Collections.Generic.IComparer<TKey>? comparer);
static member Sort : 'Key[] * 'Value[] * System.Collections.Generic.IComparer<'Key> -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue(), comparer As IComparer(Of TKey))

Parametri di tipo

TKey

Tipo degli elementi della matrice delle chiavi.

TValue

Tipo degli elementi della matrice degli elementi.

Parametri

keys
TKey[]

Oggetto Array unidimensionale in base zero che contiene le chiavi da ordinare.

items
TValue[]

Oggetto unidimensionale in base zero Array che contiene gli elementi che corrispondono alle chiavi in keys oppure null per ordinare solo keys.

comparer
IComparer<TKey>

Implementazione dell'interfaccia generica IComparer<T> da usare per il confronto fra gli elementi oppure null per usare l'implementazione dell'interfaccia generica IComparable<T> di ciascun elemento.

Eccezioni

keys è null.

items non è null e il limite inferiore di keys non corrisponde al limite inferiore di items.

-oppure-

items non è null e la lunghezza di keys è maggiore della lunghezza di items.

-oppure-

L'implementazione di comparer ha causato un errore durante l'ordinamento. Ad esempio, comparer potrebbe non restituire 0 quando si confronta un elemento con se stesso.

comparer è null, e uno o più elementi in keysArray non implementano l'interfaccia generica IComparable<T>.

Esempio

Nell'esempio di codice seguente vengono illustrati gli overload del metodo , [], Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), e Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generici, per l'ordinamento Sort<TKey,TValue>(TKey[], TValue[])di coppie di matrici che rappresentano chiavi e valori.

L'esempio di codice definisce un comparer alternativo per le stringhe, denominato ReverseCompare, che implementa l'interfaccia IComparer<string> generica (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++). Il comparer chiama il metodo, ripristinando l'ordine CompareTo(String) dei comparandi in modo che le stringhe ordinano high-to-low anziché low-to-high.

L'esempio di codice crea e visualizza una matrice di nomi di dinosauro (le chiavi) e una matrice di interi che rappresentano la lunghezza massima di ogni dinosauro in metri (i valori). Le matrici vengono quindi ordinate e visualizzate più volte:

Nota

Le chiamate ai metodi generici non sembrano diverse dalle chiamate alle loro controparti nongeneriche, perché Visual Basic, C#e C++ inferiscono il tipo del parametro di tipo generico dal tipo dei primi due argomenti. Se si usa il Ildasm.exe (IL Disassembler) per esaminare il linguaggio intermedio Microsoft (MSIL), è possibile notare che i metodi generici vengono chiamati.

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.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs =
    [| "Seismosaurus"
       "Chasmosaurus"
       "Coelophysis"
       "Mamenchisaurus"
       "Caudipteryx"
       "Cetiosaurus" |]

let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes)"
Array.Sort(dinosaurs, dinosaurSizes)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

let rc = ReverseComparer()

printfn "\nSort(dinosaurs, dinosaurSizes, rc)"
Array.Sort(dinosaurs, dinosaurSizes, rc)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

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

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

    End Sub

End Class

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

Commenti

Ogni chiave in keysArray ha un elemento corrispondente in itemsArray. Quando una chiave viene riposizionata durante l'ordinamento, l'elemento corrispondente in itemsArray viene riposizionato in modo analogo. Pertanto, l'oggetto itemsArray viene ordinato in base alla disposizione delle chiavi corrispondenti in keysArray.

Se comparer è null, ogni chiave in keysArray deve implementare l'interfaccia IComparable<T> generica per poter eseguire confronti con ogni altra chiave.

È possibile ordinare se sono presenti più elementi rispetto alle chiavi, ma gli elementi che non dispongono di chiavi corrispondenti non verranno ordinati. Non è possibile ordinare se sono presenti più chiavi di elementi; in questo modo viene generata un'eccezione ArgumentException.

Se l'ordinamento non viene completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log ), dove n è l'oggetto Length di arrayn.

Note per i chiamanti

.NET Framework 4 e versioni precedenti usavano solo l'algoritmo Quicksort. Quicksort identifica i comparer non validi in alcune situazioni in cui l'operazione di ordinamento genera un'eccezione e genera un'eccezione IndexOutOfRangeExceptionArgumentException al chiamante. A partire da .NET Framework 4.5, è possibile che le operazioni di ordinamento che in precedenza hanno generato ArgumentException non genereranno un'eccezione, perché gli algoritmi di inserimento e heapsort non rilevano un comparer non valido. Per la maggior parte, questo vale per le matrici con meno di o uguale a 16 elementi.

Vedi anche

Si applica a

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

Ordina un intervallo di elementi in una coppia di oggetti Array (uno contenente le chiavi e l'altro contenente gli elementi corrispondenti) in base alle chiavi nel primo oggetto Array usando l'implementazione dell'interfaccia generica IComparable<T> di ciascuna chiave.

public:
generic <typename TKey, typename TValue>
 static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items, int index, int length);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, int index, int length);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items, int index, int length);
static member Sort : 'Key[] * 'Value[] * int * int -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue(), index As Integer, length As Integer)

Parametri di tipo

TKey

Tipo degli elementi della matrice delle chiavi.

TValue

Tipo degli elementi della matrice degli elementi.

Parametri

keys
TKey[]

Oggetto Array unidimensionale in base zero che contiene le chiavi da ordinare.

items
TValue[]

Oggetto unidimensionale in base zero Array che contiene gli elementi che corrispondono alle chiavi in keys oppure null per ordinare solo keys.

index
Int32

Indice iniziale dell'intervallo da ordinare.

length
Int32

Numero di elementi nell'intervallo da ordinare.

Eccezioni

keys è null.

index è minore del limite inferiore di keys.

-oppure-

length è minore di zero.

items non è null e il limite inferiore di keys non corrisponde al limite inferiore di items.

-oppure-

items non è null e la lunghezza di keys è maggiore della lunghezza di items.

-oppure-

index e length non specificano un intervallo valido in keysArray.

-oppure-

items non è null e index e length non specificano un intervallo valido in itemsArray.

Uno o più elementi in keysArray non implementano l'interfaccia generica IComparable<T>.

Esempio

Nell'esempio di codice seguente vengono illustrati gli overload del metodo generico , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), e Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) per l'ordinamento Sort<TKey,TValue>(TKey[], TValue[])di coppie di matrici che rappresentano chiavi e valori.

L'esempio di codice definisce un operatore di confronto alternativo per le stringhe, denominato ReverseCompare, che implementa l'interfaccia IComparer<string> generica (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++). L'operatore di confronto chiama il CompareTo(String) metodo, ripristinando l'ordine dei comparand in modo che le stringhe ordinano l'ordinamento da alto a basso anziché da basso a basso.

L'esempio di codice crea e visualizza una matrice di nomi di dinosauro (le chiavi) e una matrice di numeri interi che rappresentano la lunghezza massima di ogni dinosauro in metri (i valori). Le matrici vengono quindi ordinate e visualizzate più volte:

Nota

Le chiamate ai metodi generici non hanno un aspetto diverso dalle chiamate alle rispettive controparti non generiche, perché Visual Basic, C# e C++ deducono il tipo del parametro di tipo generico dal tipo dei primi due argomenti. Se si usa il Ildasm.exe (Disassembler IL) per esaminare il linguaggio MSIL (Microsoft Intermediate Language), è possibile vedere che vengono chiamati i metodi generici.

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.
 */
open System
open System.Collections.Generic

type ReverseComparer() =
    interface IComparer<string> with
        member _.Compare(x, y) =
            y.CompareTo x

let dinosaurs =
    [| "Seismosaurus"
       "Chasmosaurus"
       "Coelophysis"
       "Mamenchisaurus"
       "Caudipteryx"
       "Cetiosaurus" |]

let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes)"
Array.Sort(dinosaurs, dinosaurSizes)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

let rc = ReverseComparer()

printfn "\nSort(dinosaurs, dinosaurSizes, rc)"
Array.Sort(dinosaurs, dinosaurSizes, rc)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

printfn ""
for i = 0 to dinosaurs.Length - 1 do
    printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."

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

Public Class ReverseComparer
    Implements IComparer(Of String)

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

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

    End Function
End Class

Public Class Example

    Public Shared Sub Main()

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

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

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

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

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

        Dim rc As New ReverseComparer()

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

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

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

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

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

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

    End Sub

End Class

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

Commenti

Ogni chiave in keysArray ha un elemento corrispondente in itemsArray. Quando una chiave viene riposizionata durante l'ordinamento, l'elemento corrispondente in itemsArray viene riposizionato in modo analogo. Pertanto, l'oggetto itemsArray viene ordinato in base alla disposizione delle chiavi corrispondenti in keysArray.

Ogni chiave all'interno dell'intervallo specificato di elementi in keysArray deve implementare l'interfaccia IComparable<T> generica in modo che sia in grado di confrontarsi con ogni altra chiave.

È possibile ordinare se sono presenti più elementi rispetto alle chiavi, ma gli elementi che non dispongono di chiavi corrispondenti non verranno ordinati. Non è possibile ordinare se sono presenti più chiavi di elementi; in questo modo viene generata un'eccezione ArgumentException.

Se l'ordinamento non viene completato correttamente, i risultati non sono definiti.

Questo metodo usa l'algoritmo di ordinamento introspettivo (introsort) come indicato di seguito:

  • Se la dimensione della partizione è minore o uguale a 16 elementi, usa un algoritmo di ordinamento di inserimento .

  • Se il numero di partizioni supera 2 * LogN, dove N è l'intervallo della matrice di input, usa un algoritmo Heapsort .

  • In caso contrario, usa un algoritmo Quicksort .

Questa implementazione esegue un ordinamento instabile; ovvero, se due elementi sono uguali, l'ordine potrebbe non essere mantenuto. Al contrario, un ordinamento stabile mantiene l'ordine degli elementi uguali.

Questo metodo è un'operazione O(n log n), dove n è length.

Vedi anche

Si applica a