Array.Sort Método
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Classifica os elementos em uma matriz unidimensional.
Sobrecargas
Sort(Array, Array, Int32, Int32, IComparer) |
Classifica uma gama de elementos em um par de objetos Array unidimensionais (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves no primeiro Array usando o IComparer especificado. |
Sort(Array, Int32, Int32, IComparer) |
Classifica os elementos em um intervalo de elementos em um Array unidimensional usando o IComparer especificado. |
Sort(Array, Array, Int32, Int32) |
Classifica um intervalo de elementos em um par de objetos Array unidirecionais (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves do primeiro Array usando a implementação IComparable de cada chave. |
Sort(Array, Int32, Int32) |
Classifica os elementos em um intervalo de elementos em um Array unidimensional usando a implementação IComparable de cada elemento do Array. |
Sort(Array, Array, IComparer) |
Classifica um par objetos Array unidimensionais (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves no primeiro Array usando o IComparer especificado. |
Sort(Array, Array) |
Classifica um par de objetos Array unidimensionais (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a implementação IComparable de cada chave. |
Sort(Array) |
Classifica os elementos em todo um Array unidimensional usando a implementação IComparable de cada elemento do Array. |
Sort(Array, IComparer) |
Classifica os elementos em um Array unidimensional usando o IComparer especificado. |
Sort<T>(T[]) |
Classifica os elementos em todo um Array usando a implementação de interface genérica do IComparable<T> de cada elemento do Array. |
Sort<T>(T[], IComparer<T>) |
Classifica os elementos em um Array usando a interface genérica IComparer<T> especificada. |
Sort<T>(T[], Comparison<T>) |
Classifica os elementos em um Array usando o Comparison<T> especificado. |
Sort<T>(T[], Int32, Int32) |
Classifica os elementos em um intervalo de elementos em um Array usando a implementação de interface genérica do IComparable<T> de cada elemento do Array. |
Sort<T>(T[], Int32, Int32, IComparer<T>) |
Classifica os elementos em um intervalo de elementos em um Array usando a interface genérica IComparer<T> especificada. |
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) |
Classifica uma gama de elementos em um par de objetos Array (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a interface genérica IComparer<T> especificada. |
Sort<TKey,TValue>(TKey[], TValue[]) |
Classifica um par de objetos Array (um contém as chaves e outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a implementação da interface genérica IComparable<T> de cada chave. |
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) |
Classifica um par de objetos Array (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a interface genérica IComparer<T> especificada. |
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) |
Classifica uma gama de elementos em um par de objetos Array (um contém as chaves e outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a implementação da interface genérica IComparable<T> de cada chave. |
Sort(Array, Array, Int32, Int32, IComparer)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
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)
Parâmetros
- items
- Array
O Array unidimensional que contém os itens correspondentes a cada uma das chaves no keys
Array.
- ou -
null
para classificar apenas o keys
Array.
- index
- Int32
O índice inicial do intervalo a ser classificado.
- length
- Int32
O número de elementos no intervalo a ser classificado.
- comparer
- IComparer
A implementação de IComparer a ser usada durante a comparação de elementos.
- ou -
null
para usar a implementação de IComparable de cada elemento.
Exceções
keys
é null
.
index
é menor que o limite inferior de keys
.
- ou -
length
é menor que zero.
items
não é null
, e o limite inferior de keys
não corresponde ao limite inferior de items
.
- ou -
items
não é null
, e o tamanho de keys
é maior que o tamanho de items
.
- ou -
index
e length
não especificam um intervalo válido no keys
Array.
- ou -
items
não é null
e index
e length
não especificam um intervalo válido no items
Array.
- ou -
A implementação de comparer
causou um erro durante a classificação. Por exemplo, comparer
não pode retornar 0 ao comparar um item com ele próprio.
comparer
é null
e um ou mais elementos no keys
Array não implementam a interface IComparable.
Exemplos
O exemplo de código a seguir mostra como classificar duas matrizes associadas em que a primeira matriz contém as chaves e a segunda matriz contém os valores. As classificações são feitas usando-se a comparação padrão e uma comparação personalizada que inverte a ordem de classificação. Observe que o resultado pode variar dependendo do CultureInfo atual.
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
Comentários
Cada chave no keys
Array tem um item correspondente no items
Array. Quando uma chave é reposicionada durante a classificação, o item correspondente no items
Array é reposicionado da mesma forma. Por isso, o items
Array é classificado de acordo com a organização das chaves correspondentes no keys
Array.
Se comparer
for null
, cada chave dentro do intervalo especificado de elementos no keys
Array deverá implementar a IComparable interface para ser capaz de comparações com todas as outras chaves.
É possível classificar se há mais itens do que chaves, mas os itens que não tiverem chaves correspondentes não serão classificados. Não será possível classificar se houver mais chaves do que itens; isso lança um ArgumentException.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
O .NET inclui implementações predefinidas IComparer listadas na tabela a seguir.
Implementação | Descrição |
---|---|
System.Collections.CaseInsensitiveComparer | Compara dois objetos, mas executa uma comparação sem diferenciação de maiúsculas e minúsculas de cadeias de caracteres. |
Comparer.Default | Compara os dois objetos usando as convenções de classificação da cultura atual. |
Comparer.DefaultInvariant | Compara os dois objetos usando as convenções de classificação da cultura invariável. |
Comparer<T>.Default | Compara dois objetos do tipo T usando a ordem de classificação padrão do tipo. |
Você também pode dar suporte a comparações personalizadas fornecendo uma instância de sua própria IComparer implementação para o comparer
parâmetro . O exemplo faz isso definindo uma implementação personalizada IComparer que inverte a ordem de classificação padrão e executa uma comparação de cadeia de caracteres que não diferencia maiúsculas de minúsculas.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usa um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é length
.
Notas aos Chamadores
.NET Framework 4 e versões anteriores usavam apenas o algoritmo Quicksort. Quicksort identifica comparadores inválidos em algumas situações nas quais a operação de classificação lança uma exceção IndexOutOfRangeException e lança uma exceção ArgumentException para o chamador. A partir do .NET Framework 4.5, é possível que as operações de classificação que foram lançadas ArgumentException anteriormente não gerem uma exceção, pois os algoritmos de classificação de inserção e heapsort não detectam um comparador inválido. Na maioria das vezes, isso se aplica a matrizes com menos ou igual a 16 elementos.
Confira também
- IComparer
- IComparable
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort(Array, Int32, Int32, IComparer)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
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)
Parâmetros
- index
- Int32
O índice inicial do intervalo a ser classificado.
- length
- Int32
O número de elementos no intervalo a ser classificado.
- comparer
- IComparer
A implementação de IComparer a ser usada durante a comparação de elementos.
- ou -
null
para usar a implementação de IComparable de cada elemento.
Exceções
array
é null
.
array
é multidimensional.
index
é menor que o limite inferior de array
.
- ou -
length
é menor que zero.
index
e length
não especificam um intervalo válido em array
.
- ou -
A implementação de comparer
causou um erro durante a classificação. Por exemplo, comparer
não pode retornar 0 ao comparar um item com ele próprio.
comparer
é null
, e um ou mais elementos em array
não implementam a interface IComparable.
Exemplos
O exemplo de código a seguir mostra como classificar os valores em um Array usando a comparação padrão e uma comparação personalizada que inverte a ordem de classificação. Observe que o resultado pode variar dependendo do CultureInfo atual.
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
Comentários
Se comparer
for null
, cada elemento dentro do intervalo especificado de elementos em array
deverá implementar a IComparable interface para ser capaz de comparações com todos os outros elementos em array
.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
O .NET inclui implementações predefinidas IComparer listadas na tabela a seguir.
Implementação | Descrição |
---|---|
System.Collections.CaseInsensitiveComparer | Compara dois objetos, mas executa uma comparação que não diferencia maiúsculas de minúsculas de cadeias de caracteres. |
Comparer.Default | Compara dois objetos usando as convenções de classificação da cultura atual. |
Comparer.DefaultInvariant | Compara dois objetos usando as convenções de classificação da cultura invariável. |
Comparer<T>.Default | Compara dois objetos do tipo T usando a ordem de classificação padrão do tipo. |
Você também pode dar suporte a comparações personalizadas fornecendo uma instância de sua própria IComparer implementação para o comparer
parâmetro . O exemplo faz isso definindo uma ReverseComparer
classe que inverte a ordem de classificação padrão para instâncias de um tipo e executa uma comparação de cadeia de caracteres que não diferencia maiúsculas de minúsculas.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é length
.
Notas aos Chamadores
.NET Framework 4 e versões anteriores usavam apenas o algoritmo Quicksort. Quicksort identifica comparadores inválidos em algumas situações nas quais a operação de classificação lança uma exceção IndexOutOfRangeException e lança uma exceção ArgumentException para o chamador. A partir do .NET Framework 4.5, é possível que as operações de classificação que foram lançadas ArgumentException anteriormente não gerem uma exceção, pois os algoritmos de classificação de inserção e heapsort não detectam um comparador inválido. Na maioria das vezes, isso se aplica a matrizes com menos ou igual a 16 elementos.
Confira também
- IComparer
- IComparable
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort(Array, Array, Int32, Int32)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica um intervalo de elementos em um par de objetos Array unidirecionais (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves do primeiro Array usando a implementação IComparable de cada chave.
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)
Parâmetros
- items
- Array
O Array unidimensional que contém os itens correspondentes a cada uma das chaves no keys
Array.
- ou -
null
para classificar apenas o keys
Array.
- index
- Int32
O índice inicial do intervalo a ser classificado.
- length
- Int32
O número de elementos no intervalo a ser classificado.
Exceções
keys
é null
.
index
é menor que o limite inferior de keys
.
- ou -
length
é menor que zero.
items
não é null
, e o tamanho de keys
é maior que o tamanho de items
.
- ou -
index
e length
não especificam um intervalo válido no keys
Array.
- ou -
items
não é null
e index
e length
não especificam um intervalo válido no items
Array.
Um ou mais elementos no keys
Array não implementam a interface IComparable.
Exemplos
O exemplo de código a seguir mostra como classificar duas matrizes associadas em que a primeira matriz contém as chaves e a segunda matriz contém os valores. As classificações são feitas usando-se a comparação padrão e uma comparação personalizada que inverte a ordem de classificação. Observe que o resultado pode variar dependendo do CultureInfo atual.
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
Comentários
Cada chave no keys
Array tem um item correspondente no items
Array. Quando uma chave é reposicionada durante a classificação, o item correspondente no items
Array é reposicionado da mesma forma. Por isso, o items
Array é classificado de acordo com a organização das chaves correspondentes no keys
Array.
Cada chave dentro do intervalo especificado de elementos no keys
Array deve implementar a IComparable interface para ser capaz de comparações com todas as outras chaves.
É possível classificar se há mais itens do que chaves, mas os itens que não tiverem chaves correspondentes não serão classificados. Não será possível classificar se houver mais chaves do que itens; isso lança um ArgumentException.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é length
.
Confira também
- IComparable
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort(Array, Int32, Int32)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica os elementos em um intervalo de elementos em um Array unidimensional usando a implementação IComparable de cada elemento do 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)
Parâmetros
- index
- Int32
O índice inicial do intervalo a ser classificado.
- length
- Int32
O número de elementos no intervalo a ser classificado.
Exceções
array
é null
.
array
é multidimensional.
index
é menor que o limite inferior de array
.
- ou -
length
é menor que zero.
index
e length
não especificam um intervalo válido em array
.
Um ou mais elementos em array
não implementam a interface IComparable.
Exemplos
O exemplo de código a seguir mostra como classificar os valores em um Array usando a comparação padrão e uma comparação personalizada que inverte a ordem de classificação. Observe que o resultado pode variar dependendo do CultureInfo atual.
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
Comentários
Cada elemento dentro do intervalo especificado de elementos em array
deve implementar a IComparable interface para ser capaz de comparações com todos os outros elementos em array
.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é length
.
Confira também
- IComparable
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort(Array, Array, IComparer)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
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)
Parâmetros
- items
- Array
O Array unidimensional que contém os itens correspondentes a cada uma das chaves no keys
Array.
- ou -
null
para classificar apenas o keys
Array.
- comparer
- IComparer
A implementação de IComparer a ser usada durante a comparação de elementos.
- ou -
null
para usar a implementação de IComparable de cada elemento.
Exceções
keys
é null
.
items
não é null
, e o tamanho de keys
é maior que o tamanho de items
.
- ou -
A implementação de comparer
causou um erro durante a classificação. Por exemplo, comparer
não pode retornar 0 ao comparar um item com ele próprio.
comparer
é null
e um ou mais elementos no keys
Array não implementam a interface IComparable.
Exemplos
O exemplo a seguir mostra como classificar duas matrizes associadas em que a primeira matriz contém as chaves e a segunda matriz contém os valores. As classificações são feitas usando-se a comparação padrão e uma comparação personalizada que inverte a ordem de classificação. Observe que o resultado pode variar dependendo do CultureInfo atual.
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
Comentários
Cada chave no keys
Array tem um item correspondente no items
Array. Quando uma chave é reposicionada durante a classificação, o item correspondente no items
Array é reposicionado da mesma forma. Por isso, o items
Array é classificado de acordo com a organização das chaves correspondentes no keys
Array.
Se comparer
for null
, cada chave no keys
Array deverá implementar a IComparable interface para ser capaz de comparações com todas as outras chaves.
É possível classificar se há mais itens do que chaves, mas os itens que não tiverem chaves correspondentes não serão classificados. Não será possível classificar se houver mais chaves do que itens; isso lança um ArgumentException.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
O .NET inclui implementações predefinidas IComparer listadas na tabela a seguir.
Implementação | Descrição |
---|---|
System.Collections.CaseInsensitiveComparer | Compara dois objetos, mas executa uma comparação que não diferencia maiúsculas de minúsculas de cadeias de caracteres. |
Comparer.Default | Compara dois objetos usando as convenções de classificação da cultura atual. |
Comparer.DefaultInvariant | Compara dois objetos usando as convenções de classificação da cultura invariável. |
Comparer<T>.Default | Compara dois objetos do tipo T usando a ordem de classificação padrão do tipo. |
Você também pode dar suporte a comparações personalizadas fornecendo uma instância de sua própria IComparer implementação para o comparer
parâmetro . O exemplo faz isso definindo uma IComparer implementação que inverte a ordem de classificação padrão e executa uma comparação de cadeia de caracteres que não diferencia maiúsculas de minúsculas.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é o Length de keys
.
Notas aos Chamadores
.NET Framework 4 e versões anteriores usavam apenas o algoritmo Quicksort. Quicksort identifica comparadores inválidos em algumas situações nas quais a operação de classificação lança uma exceção IndexOutOfRangeException e lança uma exceção ArgumentException para o chamador. A partir do .NET Framework 4.5, é possível que as operações de classificação que foram lançadas ArgumentException anteriormente não gerem uma exceção, pois a classificação de inserção e os algoritmos heapsort não detectam um comparador inválido. Na maioria das vezes, isso se aplica a matrizes com menos ou igual a 16 elementos.
Confira também
- IComparer
- IComparable
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort(Array, Array)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica um par de objetos Array unidimensionais (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a implementação IComparable de cada chave.
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)
Parâmetros
- items
- Array
O Array unidimensional que contém os itens correspondentes a cada uma das chaves no keys
Array.
- ou -
null
para classificar apenas o keys
Array.
Exceções
keys
é null
.
items
não é null
, e o tamanho de keys
é maior que o tamanho de items
.
Um ou mais elementos no keys
Array não implementam a interface IComparable.
Exemplos
O exemplo a seguir mostra como classificar duas matrizes associadas em que a primeira matriz contém as chaves e a segunda matriz contém os valores. As classificações são feitas usando-se a comparação padrão e uma comparação personalizada que inverte a ordem de classificação. Observe que o resultado pode variar dependendo do CultureInfo atual.
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
Comentários
Cada chave no keys
Array tem um item correspondente no items
Array. Quando uma chave é reposicionada durante a classificação, o item correspondente no items
Array é reposicionado da mesma forma. Por isso, o items
Array é classificado de acordo com a organização das chaves correspondentes no keys
Array.
Cada chave no keys
Array deve implementar a IComparable interface para ser capaz de comparações com todas as outras chaves.
É possível classificar se há mais itens do que chaves, mas os itens que não tiverem chaves correspondentes não serão classificados. Não será possível classificar se houver mais chaves do que itens; isso lança um ArgumentException.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é o Length de keys
.
Confira também
- IComparable
- BinarySearch
- IDictionary
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort(Array)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica os elementos em todo um Array unidimensional usando a implementação IComparable de cada elemento do 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)
Parâmetros
Exceções
array
é null
.
array
é multidimensional.
Um ou mais elementos em array
não implementam a interface IComparable.
Exemplos
O exemplo de código a seguir mostra como classificar os valores em um Array usando a comparação padrão e uma comparação personalizada que inverte a ordem de classificação. Observe que o resultado pode variar dependendo do CultureInfo atual.
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
Comentários
Cada elemento de array
deve implementar a IComparable interface para ser capaz de comparações com todos os outros elementos em array
.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é o Length de array
.
Confira também
- IComparable
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort(Array, IComparer)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
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)
Parâmetros
- array
- Array
A matriz unidimensional a ser classificada.
- comparer
- IComparer
A implementação a ser usada ao comparar elementos.
- ou -
null
para usar a implementação de IComparable de cada elemento.
Exceções
array
é null
.
array
é multidimensional.
comparer
é null
, e um ou mais elementos em array
não implementam a interface IComparable.
A implementação de comparer
causou um erro durante a classificação. Por exemplo, comparer
não pode retornar 0 ao comparar um item com ele próprio.
Exemplos
O exemplo a seguir classifica os valores em uma matriz de cadeia de caracteres usando o comparador padrão. Ele também define uma implementação personalizada IComparer chamada ReverseComparer
que inverte a ordem de classificação padrão de um objeto ao executar uma comparação de cadeia de caracteres que não diferencia maiúsculas de minúsculas. Observe que a saída pode variar dependendo da cultura atual.
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
Comentários
Se comparer
for null
, cada elemento de array
deverá implementar a IComparable interface para ser capaz de comparações com todos os outros elementos em array
.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é o Length de array
.
O .NET inclui implementações predefinidas IComparer listadas na tabela a seguir.
Implementação | Descrição |
---|---|
System.Collections.CaseInsensitiveComparer | Compara dois objetos, mas executa uma comparação que não diferencia maiúsculas de minúsculas de cadeias de caracteres. |
Comparer.Default | Compara dois objetos usando as convenções de classificação da cultura atual. |
Comparer.DefaultInvariant | Compara dois objetos usando as convenções de classificação da cultura invariável. |
Comparer<T>.Default | Compara dois objetos do tipo T usando a ordem de classificação padrão do tipo. |
Você também pode dar suporte a comparações personalizadas fornecendo uma instância de sua própria IComparer implementação para o comparer
parâmetro . O exemplo faz isso definindo uma ReverseComparer
classe que inverte a ordem de classificação padrão para instâncias de um tipo e executa uma comparação de cadeia de caracteres que não diferencia maiúsculas de minúsculas.
Notas aos Chamadores
.NET Framework 4 e versões anteriores usavam apenas o algoritmo Quicksort. Quicksort identifica comparadores inválidos em algumas situações nas quais a operação de classificação lança uma exceção IndexOutOfRangeException e lança uma exceção ArgumentException para o chamador. A partir do .NET Framework 4.5, é possível que as operações de classificação que foram lançadas ArgumentException anteriormente não gerem uma exceção, pois a classificação de inserção e os algoritmos heapsort não detectam um comparador inválido. Na maioria das vezes, isso se aplica a matrizes com menos ou igual a 16 elementos.
Confira também
- IComparer
- IComparable
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort<T>(T[])
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica os elementos em todo um Array usando a implementação de interface genérica do IComparable<T> de cada elemento do Array.
public:
generic <typename T>
static void Sort(cli::array <T> ^ array);
public static void Sort<T> (T[] array);
static member Sort : 'T[] -> unit
Public Shared Sub Sort(Of T) (array As T())
Parâmetros de tipo
- T
O tipo dos elementos da matriz.
Parâmetros
- array
- T[]
O Array unidimensional baseado em zero a ser classificado.
Exceções
array
é null
.
Um ou mais elementos em array
não implementam a interface genérica IComparable<T>.
Exemplos
O exemplo de código a seguir demonstra a sobrecarga de Sort<T>(T[]) método genérico e a sobrecarga de BinarySearch<T>(T[], T) método genérico. Uma matriz de cadeias de caracteres é criada, em nenhuma ordem específica.
A matriz é exibida, classificada e exibida novamente.
Observação
As chamadas para os métodos genéricos Sort e BinarySearch não são diferentes de chamadas para seus equivalentes não genéricos, porque o Visual Basic, o C# e o C++ inferem o tipo de parâmetro de tipo genérico a partir do tipo do primeiro argumento. Se você usar o Ildasm.exe (IL Disassembler) para examinar a MSIL (Linguagem Intermediária da Microsoft), poderá ver que os métodos genéricos estão sendo chamados.
Em BinarySearch<T>(T[], T) seguida, a sobrecarga de método genérico é usada para pesquisar duas cadeias de caracteres, uma que não está na matriz e outra. A matriz e o valor retornado do BinarySearch método são passados para o ShowWhere
método genérico, que exibe o valor do índice se a cadeia de caracteres for encontrada e, caso contrário, os elementos entre os quais a cadeia de caracteres de pesquisa ficaria se estivesse na matriz. O índice é negativo caso a cadeia de caracteres não seja n na matriz, logo, o método ShowWhere
usa o complemento bit a bit (o operador ~ no C# e no Visual C++, Xor
-1 no Visual Basic) para obter o índice do primeiro elemento na lista que é maior do que a cadeia de caracteres de pesquisa.
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.
Comentários
Cada elemento de array
deve implementar a IComparable<T> interface genérica para ser capaz de comparações com todos os outros elementos em array
.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é o Length de array
.
Confira também
- IComparable<T>
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort<T>(T[], IComparer<T>)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica os elementos em um Array usando a interface genérica IComparer<T> especificada.
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))
Parâmetros de tipo
- T
O tipo dos elementos da matriz.
Parâmetros
- array
- T[]
A base Array unidimensional zero a ser classificada.
- comparer
- IComparer<T>
A implementação genérica da interface IComparer<T> a ser usada na comparação de elementos ou null
para usar a implementação genérica da interface IComparable<T> de cada elemento.
Exceções
array
é null
.
comparer
é null
e um ou mais elementos em array
não implementam a interface genérica IComparable<T>.
A implementação de comparer
causou um erro durante a classificação. Por exemplo, comparer
não pode retornar 0 ao comparar um item com ele próprio.
Exemplos
O exemplo de código a seguir demonstra a sobrecarga de Sort<T>(T[], IComparer<T>) método genérico e a sobrecarga de BinarySearch<T>(T[], T, IComparer<T>) método genérico.
O exemplo de código define uma comparação alternativa para cadeias de caracteres, chamada ReverseCompare
, que implementa a interface genérica IComparer<string>
(IComparer(Of String)
no Visual Basic, IComparer<String^>
no Visual C++). A comparação chama o método CompareTo(String), invertendo a ordem dos comparandos de modo que as cadeias de caracteres sejam classificadas da maior para a menor, e não o contrário.
A matriz é exibida, classificada e exibida novamente. As matrizes devem ser classificadas para usar o BinarySearch método .
Observação
As chamadas para os métodos genéricos Sort<T>(T[], IComparer<T>) e BinarySearch<T>(T[], T, IComparer<T>) não são diferentes de chamadas para seus equivalentes não genéricos, porque o Visual Basic, o C# e o C++ inferem o tipo de parâmetro de tipo genérico a partir do tipo do primeiro argumento. Se você usar o Ildasm.exe (IL Disassembler) para examinar a MSIL (Linguagem Intermediária da Microsoft), poderá ver que os métodos genéricos estão sendo chamados.
Em BinarySearch<T>(T[], T, IComparer<T>) seguida, a sobrecarga de método genérico é usada para pesquisar duas cadeias de caracteres, uma que não está na matriz e outra. A matriz e o valor retornado do BinarySearch<T>(T[], T, IComparer<T>) método são passados para o ShowWhere
método genérico, que exibe o valor do índice se a cadeia de caracteres for encontrada e, caso contrário, os elementos entre os quais a cadeia de caracteres de pesquisa ficaria se estivesse na matriz. O índice é negativo caso a cadeia de caracteres não seja n na matriz, logo, o método ShowWhere
usa o complemento bit a bit (o operador ~ no C# e no Visual C++, Xor
-1 no Visual Basic) para obter o índice do primeiro elemento na lista que é maior do que a cadeia de caracteres de pesquisa.
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.
Comentários
Se comparer
for null
, cada elemento de array
deverá implementar a IComparable<T> interface genérica para ser capaz de comparações com todos os outros elementos em array
.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é o Length de array
.
Notas aos Chamadores
.NET Framework 4 e versões anteriores usavam apenas o algoritmo Quicksort. Quicksort identifica comparadores inválidos em algumas situações nas quais a operação de classificação lança uma exceção IndexOutOfRangeException e lança uma exceção ArgumentException para o chamador. A partir do .NET Framework 4.5, é possível que as operações de classificação que foram lançadas ArgumentException anteriormente não gerem uma exceção, pois a classificação de inserção e os algoritmos heapsort não detectam um comparador inválido. Na maioria das vezes, isso se aplica a matrizes com menos ou igual a 16 elementos.
Confira também
- IComparer<T>
- IComparable<T>
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort<T>(T[], Comparison<T>)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica os elementos em um Array usando o Comparison<T> especificado.
public:
generic <typename T>
static void Sort(cli::array <T> ^ array, Comparison<T> ^ comparison);
public static void Sort<T> (T[] array, Comparison<T> comparison);
static member Sort : 'T[] * Comparison<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), comparison As Comparison(Of T))
Parâmetros de tipo
- T
O tipo dos elementos da matriz.
Parâmetros
- array
- T[]
O Array unidimensional baseado em zero a ser classificado.
- comparison
- Comparison<T>
O Comparison<T> a ser usado na comparação de elementos.
Exceções
A implementação de comparison
causou um erro durante a classificação. Por exemplo, comparison
não pode retornar 0 ao comparar um item com ele próprio.
Exemplos
O exemplo de código a seguir demonstra a sobrecarga do Sort(Comparison<T>) método.
O exemplo de código define um método de comparação alternativo para cadeias de caracteres, chamado CompareDinosByLength
. Esse método funciona da seguinte maneira: primeiro, os comparands são testados enull
uma referência nula é tratada como menor que um não nulo. Em segundo lugar, os comprimentos da cadeia de caracteres são comparados e a cadeia de caracteres mais longa é considerada maior. Em terceiro lugar, se os comprimentos forem iguais, a comparação de cadeia de caracteres comum será usada.
Uma matriz de cadeias de caracteres é criada e preenchida com quatro cadeias de caracteres, em nenhuma ordem específica. A lista também inclui uma cadeia de caracteres vazia e uma referência nula. A lista é exibida, classificada usando um Comparison<T> delegado genérico que representa o CompareDinosByLength
método e exibida novamente.
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"
Comentários
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é o Length de array
.
Notas aos Chamadores
.NET Framework 4 e versões anteriores usavam apenas o algoritmo Quicksort. Quicksort identifica comparadores inválidos em algumas situações nas quais a operação de classificação lança uma exceção IndexOutOfRangeException e lança uma exceção ArgumentException para o chamador. A partir do .NET Framework 4.5, é possível que as operações de classificação que foram lançadas ArgumentException anteriormente não gerem uma exceção, pois a classificação de inserção e os algoritmos heapsort não detectam um comparador inválido. Na maioria das vezes, isso se aplica a matrizes com menos ou igual a 6 elementos.
Confira também
- Comparison<T>
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort<T>(T[], Int32, Int32)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica os elementos em um intervalo de elementos em um Array usando a implementação de interface genérica do IComparable<T> de cada elemento do Array.
public:
generic <typename T>
static void Sort(cli::array <T> ^ array, int index, int length);
public static void Sort<T> (T[] array, int index, int length);
static member Sort : 'T[] * int * int -> unit
Public Shared Sub Sort(Of T) (array As T(), index As Integer, length As Integer)
Parâmetros de tipo
- T
O tipo dos elementos da matriz.
Parâmetros
- array
- T[]
O Array unidimensional baseado em zero a ser classificado.
- index
- Int32
O índice inicial do intervalo a ser classificado.
- length
- Int32
O número de elementos no intervalo a ser classificado.
Exceções
array
é null
.
index
é menor que o limite inferior de array
.
- ou -
length
é menor que zero.
index
e length
não especificam um intervalo válido em array
.
Um ou mais elementos em array
não implementam a interface genérica IComparable<T>.
Exemplos
O exemplo de código a seguir demonstra a sobrecarga de Sort<T>(T[], Int32, Int32) método genérico e a sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) método genérico para classificar um intervalo em uma matriz.
O exemplo de código define uma comparação alternativa para cadeias de caracteres, chamada ReverseCompare
, que implementa a interface genérica IComparer<string>
(IComparer(Of String)
no Visual Basic, IComparer<String^>
no Visual C++). A comparação chama o método CompareTo(String), invertendo a ordem dos comparandos de modo que as cadeias de caracteres sejam classificadas da maior para a menor, e não o contrário.
O exemplo de código cria e exibe uma matriz de nomes de dinossauros, consistindo em três herbívoros seguidos por três carnívoros (tiranossauros, para ser preciso). A Sort<T>(T[], Int32, Int32) sobrecarga de método genérico é usada para classificar os últimos três elementos da matriz, que é exibida em seguida. A Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) sobrecarga de método genérico é usada com ReverseCompare
para classificar os últimos três elementos em ordem inversa. Os dinossauros completamente confusos são exibidos novamente.
Observação
As chamadas para os métodos genéricos Sort<T>(T[], IComparer<T>) e BinarySearch<T>(T[], T, IComparer<T>) não são diferentes de chamadas para seus equivalentes não genéricos, porque o Visual Basic, o C# e o C++ inferem o tipo de parâmetro de tipo genérico a partir do tipo do primeiro argumento. Se você usar o Ildasm.exe (IL Disassembler) para examinar a MSIL (Linguagem Intermediária da Microsoft), poderá ver que os métodos genéricos estão sendo chamados.
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
Comentários
Cada elemento dentro do intervalo especificado de elementos em array
deve implementar a IComparable<T> interface genérica para ser capaz de comparações com todos os outros elementos em array
.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é length
.
Confira também
- IComparable<T>
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort<T>(T[], Int32, Int32, IComparer<T>)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica os elementos em um intervalo de elementos em um Array usando a interface genérica IComparer<T> especificada.
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))
Parâmetros de tipo
- T
O tipo dos elementos da matriz.
Parâmetros
- array
- T[]
O Array unidimensional baseado em zero a ser classificado.
- index
- Int32
O índice inicial do intervalo a ser classificado.
- length
- Int32
O número de elementos no intervalo a ser classificado.
- comparer
- IComparer<T>
A implementação genérica da interface IComparer<T> a ser usada na comparação de elementos ou null
para usar a implementação genérica da interface IComparable<T> de cada elemento.
Exceções
array
é null
.
index
é menor que o limite inferior de array
.
- ou -
length
é menor que zero.
index
e length
não especificam um intervalo válido em array
.
- ou -
A implementação de comparer
causou um erro durante a classificação. Por exemplo, comparer
não pode retornar 0 ao comparar um item com ele próprio.
comparer
é null
e um ou mais elementos em array
não implementam a interface genérica IComparable<T>.
Exemplos
O exemplo de código a seguir demonstra a sobrecarga de Sort<T>(T[], Int32, Int32) método genérico e a sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) método genérico para classificar um intervalo em uma matriz.
O exemplo de código define uma comparação alternativa para cadeias de caracteres, chamada ReverseCompare
, que implementa a interface genérica IComparer<string>
(IComparer(Of String)
no Visual Basic, IComparer<String^>
no Visual C++). A comparação chama o método CompareTo(String), invertendo a ordem dos comparandos de modo que as cadeias de caracteres sejam classificadas da maior para a menor, e não o contrário.
O exemplo de código cria e exibe uma matriz de nomes de dinossauros, consistindo em três herbívoros seguidos por três carnívoros (tiranossauros, para ser preciso). A Sort<T>(T[], Int32, Int32) sobrecarga de método genérico é usada para classificar os últimos três elementos da matriz, que é exibida em seguida. A Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) sobrecarga de método genérico é usada com ReverseCompare
para classificar os últimos três elementos em ordem inversa. Os dinossauros completamente confusos são exibidos novamente.
Observação
As chamadas para os métodos genéricos Sort<T>(T[], IComparer<T>) e BinarySearch<T>(T[], T, IComparer<T>) não são diferentes de chamadas para seus equivalentes não genéricos, porque o Visual Basic, o C# e o C++ inferem o tipo de parâmetro de tipo genérico a partir do tipo do primeiro argumento. Se você usar o Ildasm.exe (IL Disassembler) para examinar a MSIL (Linguagem Intermediária da Microsoft), poderá ver que os métodos genéricos estão sendo chamados.
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
Comentários
Se comparer
for null
, cada elemento dentro do intervalo especificado de elementos em array
deverá implementar a IComparable<T> interface genérica para ser capaz de comparações com todos os outros elementos em array
.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é length
.
Notas aos Chamadores
.NET Framework 4 e versões anteriores usavam apenas o algoritmo Quicksort. Quicksort identifica comparadores inválidos em algumas situações nas quais a operação de classificação lança uma exceção IndexOutOfRangeException e lança uma exceção ArgumentException para o chamador. A partir do .NET Framework 4.5, é possível que as operações de classificação que foram lançadas ArgumentException anteriormente não gerem uma exceção, pois a classificação de inserção e os algoritmos heapsort não detectam um comparador inválido. Na maioria das vezes, isso se aplica a matrizes com menos ou igual a 16 elementos.
Confira também
- IComparer<T>
- IComparable<T>
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica uma gama de elementos em um par de objetos Array (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a interface genérica IComparer<T> especificada.
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))
Parâmetros de tipo
- TKey
O tipo dos elementos da matriz principal.
- TValue
O tipo dos elementos da matriz de itens.
Parâmetros
- keys
- TKey[]
O Array unidimensional, com base em zero, que contém as chaves a serem classificadas.
- items
- TValue[]
O Array unidimensional, com base em zero, que contém os itens correspondentes às chaves em keys
ou null
para classificar somente keys
.
- index
- Int32
O índice inicial do intervalo a ser classificado.
- length
- Int32
O número de elementos no intervalo a ser classificado.
- comparer
- IComparer<TKey>
A implementação genérica da interface IComparer<T> a ser usada na comparação de elementos ou null
para usar a implementação genérica da interface IComparable<T> de cada elemento.
Exceções
keys
é null
.
index
é menor que o limite inferior de keys
.
- ou -
length
é menor que zero.
items
não é null
, e o limite inferior de keys
não corresponde ao limite inferior de items
.
- ou -
items
não é null
, e o tamanho de keys
é maior que o tamanho de items
.
- ou -
index
e length
não especificam um intervalo válido no keys
Array.
- ou -
items
não é null
e index
e length
não especificam um intervalo válido no items
Array.
- ou -
A implementação de comparer
causou um erro durante a classificação. Por exemplo, comparer
não pode retornar 0 ao comparar um item com ele próprio.
comparer
é null
e um ou mais elementos no keys
Array não implementam a interface genérica IComparable<T>.
Exemplos
O exemplo de código a seguir demonstra as sobrecargas de método genérico Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) e Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) para pares de matrizes de classificação que representam chaves e valores.
O exemplo de código define um comparador alternativo para cadeias de caracteres, chamado ReverseCompare
, que implementa a IComparer<string>
interface genérica (IComparer(Of String)
no Visual Basic, IComparer<String^>
no Visual C++). A comparação chama o método CompareTo(String), invertendo a ordem dos comparandos de modo que as cadeias de caracteres sejam classificadas da maior para a menor, e não o contrário.
O exemplo de código cria e exibe uma matriz de nomes de dinossauros (as chaves) e uma matriz de inteiros que representam o tamanho máximo de cada dinossauro em metros (os valores). Em seguida, as matrizes são classificadas e exibidas várias vezes:
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[]) é usada para classificar ambas as matrizes na ordem dos nomes de dinossauros na primeira matriz.
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) e uma instância de
ReverseCompare
são usadas para inverter a ordem de classificação de matrizes pareadas.A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) é usada para classificar os últimos três elementos de ambas as matrizes.
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) é usada para classificar os três elementos mais recentes de ambas as matrizes na ordem inversa.
Observação
As chamadas para os métodos genéricos não têm diferenças em relação a chamadas para os equivalentes não genéricos, porque o Visual Basic, o C# e o C++ inferem o tipo do parâmetro de tipo genérico do tipo dos dois primeiros argumentos. Se você usar o Ildasm.exe (IL Disassembler) para examinar a MSIL (Linguagem Intermediária da Microsoft), poderá ver que os métodos genéricos estão sendo chamados.
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.
Comentários
Cada chave no keys
Array tem um item correspondente no items
Array. Quando uma chave é reposicionada durante a classificação, o item correspondente no items
Array é reposicionado da mesma forma. Por isso, o items
Array é classificado de acordo com a organização das chaves correspondentes no keys
Array.
Se comparer
for null
, cada chave dentro do intervalo especificado de elementos no keys
Array deverá implementar a IComparable<T> interface genérica para ser capaz de comparações com todas as outras chaves.
É possível classificar se há mais itens do que chaves, mas os itens que não tiverem chaves correspondentes não serão classificados. Não será possível classificar se houver mais chaves do que itens; isso lança um ArgumentException.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Este método usa o algoritmo introspective sort (introsort) da seguinte forma:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é length
.
Notas aos Chamadores
.NET Framework 4 e versões anteriores usavam apenas o algoritmo Quicksort. Quicksort identifica comparadores inválidos em algumas situações nas quais a operação de classificação lança uma exceção IndexOutOfRangeException e lança uma exceção ArgumentException para o chamador. A partir do .NET Framework 4.5, é possível que as operações de classificação que foram lançadas ArgumentException anteriormente não gerem uma exceção, pois a classificação de inserção e os algoritmos heapsort não detectam um comparador inválido. Na maioria das vezes, isso se aplica a matrizes com menos ou igual a 16 elementos.
Confira também
- IComparer<T>
- IComparable<T>
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort<TKey,TValue>(TKey[], TValue[])
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica um par de objetos Array (um contém as chaves e outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a implementação da interface genérica IComparable<T> de cada chave.
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())
Parâmetros de tipo
- TKey
O tipo dos elementos da matriz principal.
- TValue
O tipo dos elementos da matriz de itens.
Parâmetros
- keys
- TKey[]
O Array unidimensional, com base em zero, que contém as chaves a serem classificadas.
- items
- TValue[]
O Array unidimensional, com base em zero, que contém os itens correspondentes às chaves em keys
ou null
para classificar somente keys
.
Exceções
keys
é null
.
items
não é null
, e o limite inferior de keys
não corresponde ao limite inferior de items
.
- ou -
items
não é null
, e o tamanho de keys
é maior que o tamanho de items
.
Um ou mais elementos no keys
Array não implementam a interface genérica IComparable<T>.
Exemplos
O exemplo de código a seguir demonstra as sobrecargas de método genérico Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) e Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) para pares de matrizes de classificação que representam chaves e valores.
O exemplo de código define uma comparação alternativa para cadeias de caracteres, chamada ReverseCompare
, que implementa a interface genérica IComparer<string>
(IComparer(Of String)
no Visual Basic, IComparer<String^>
no Visual C++). A comparação chama o método CompareTo(String), invertendo a ordem dos comparandos de modo que as cadeias de caracteres sejam classificadas da maior para a menor, e não o contrário.
O exemplo de código cria e exibe uma matriz de nomes de dinossauros (as chaves) e uma matriz de inteiros que representam o tamanho máximo de cada dinossauro em metros (os valores). Em seguida, as matrizes são classificadas e exibidas várias vezes:
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[]) é usada para classificar ambas as matrizes na ordem dos nomes de dinossauros na primeira matriz.
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) e uma instância de
ReverseCompare
são usadas para inverter a ordem de classificação de matrizes pareadas.A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) é usada para classificar os últimos três elementos de ambas as matrizes.
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) é usada para classificar os três elementos mais recentes de ambas as matrizes na ordem inversa.
Observação
As chamadas para os métodos genéricos não têm diferenças em relação a chamadas para os equivalentes não genéricos, porque o Visual Basic, o C# e o C++ inferem o tipo do parâmetro de tipo genérico do tipo dos dois primeiros argumentos. Se você usar o Ildasm.exe (IL Disassembler) para examinar a MSIL (Linguagem Intermediária da Microsoft), poderá ver que os métodos genéricos estão sendo chamados.
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.
Comentários
Cada chave no keys
Array tem um item correspondente no items
Array. Quando uma chave é reposicionada durante a classificação, o item correspondente no items
Array é reposicionado da mesma forma. Por isso, o items
Array é classificado de acordo com a organização das chaves correspondentes no keys
Array.
Cada chave no keys
Array deve implementar a IComparable<T> interface genérica para ser capaz de comparações com todas as outras chaves.
É possível classificar se há mais itens do que chaves, mas os itens que não tiverem chaves correspondentes não serão classificados. Não será possível classificar se houver mais chaves do que itens; isso lança um ArgumentException.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é o Length de array
.
Confira também
- IComparable<T>
- BinarySearch
- IDictionary<TKey,TValue>
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica um par de objetos Array (um contém as chaves e o outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a interface genérica IComparer<T> especificada.
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))
Parâmetros de tipo
- TKey
O tipo dos elementos da matriz principal.
- TValue
O tipo dos elementos da matriz de itens.
Parâmetros
- keys
- TKey[]
O Array unidimensional, com base em zero, que contém as chaves a serem classificadas.
- items
- TValue[]
O Array unidimensional, com base em zero, que contém os itens correspondentes às chaves em keys
ou null
para classificar somente keys
.
- comparer
- IComparer<TKey>
A implementação genérica da interface IComparer<T> a ser usada na comparação de elementos ou null
para usar a implementação genérica da interface IComparable<T> de cada elemento.
Exceções
keys
é null
.
items
não é null
, e o limite inferior de keys
não corresponde ao limite inferior de items
.
- ou -
items
não é null
, e o tamanho de keys
é maior que o tamanho de items
.
- ou -
A implementação de comparer
causou um erro durante a classificação. Por exemplo, comparer
não pode retornar 0 ao comparar um item com ele próprio.
comparer
é null
e um ou mais elementos no keys
Array não implementam a interface genérica IComparable<T>.
Exemplos
O exemplo de código a seguir demonstra as Sort<TKey,TValue>(TKey[], TValue[])sobrecargas de método genérico , [], Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), e Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) , para classificar pares de matrizes que representam chaves e valores.
O exemplo de código define uma comparação alternativa para cadeias de caracteres, chamada ReverseCompare
, que implementa a interface genérica IComparer<string>
(IComparer(Of String)
no Visual Basic, IComparer<String^>
no Visual C++). A comparação chama o método CompareTo(String), invertendo a ordem dos comparandos de modo que as cadeias de caracteres sejam classificadas da maior para a menor, e não o contrário.
O exemplo de código cria e exibe uma matriz de nomes de dinossauros (as chaves) e uma matriz de inteiros que representam o tamanho máximo de cada dinossauro em metros (os valores). Em seguida, as matrizes são classificadas e exibidas várias vezes:
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[]) é usada para classificar ambas as matrizes na ordem dos nomes de dinossauros na primeira matriz.
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) e uma instância de
ReverseCompare
são usadas para inverter a ordem de classificação de matrizes pareadas.A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) é usada para classificar os últimos três elementos de ambas as matrizes.
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) é usada para classificar os três elementos mais recentes de ambas as matrizes na ordem inversa.
Observação
As chamadas para os métodos genéricos não têm diferenças em relação a chamadas para os equivalentes não genéricos, porque o Visual Basic, o C# e o C++ inferem o tipo do parâmetro de tipo genérico do tipo dos dois primeiros argumentos. Se você usar o Ildasm.exe (IL Disassembler) para examinar a MSIL (Linguagem Intermediária da Microsoft), poderá ver que os métodos genéricos estão sendo chamados.
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.
Comentários
Cada chave no keys
Array tem um item correspondente no items
Array. Quando uma chave é reposicionada durante a classificação, o item correspondente no items
Array é reposicionado da mesma forma. Por isso, o items
Array é classificado de acordo com a organização das chaves correspondentes no keys
Array.
Se comparer
for null
, cada chave no keys
Array deverá implementar a IComparable<T> interface genérica para ser capaz de comparações com todas as outras chaves.
É possível classificar se há mais itens do que chaves, mas os itens que não tiverem chaves correspondentes não serão classificados. Não será possível classificar se houver mais chaves do que itens; isso lança um ArgumentException.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é o Length de array
.
Notas aos Chamadores
.NET Framework 4 e versões anteriores usavam apenas o algoritmo Quicksort. Quicksort identifica comparadores inválidos em algumas situações nas quais a operação de classificação lança uma exceção IndexOutOfRangeException e lança uma exceção ArgumentException para o chamador. A partir do .NET Framework 4.5, é possível que as operações de classificação que foram lançadas ArgumentException anteriormente não gerem uma exceção, pois a classificação de inserção e os algoritmos heapsort não detectam um comparador inválido. Na maioria das vezes, isso se aplica a matrizes com menos ou igual a 16 elementos.
Confira também
- IComparer<T>
- IComparable<T>
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)
- Origem:
- Array.cs
- Origem:
- Array.cs
- Origem:
- Array.cs
Classifica uma gama de elementos em um par de objetos Array (um contém as chaves e outro contém os itens correspondentes) com base nas chaves no primeiro Array usando a implementação da interface genérica IComparable<T> de cada chave.
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)
Parâmetros de tipo
- TKey
O tipo dos elementos da matriz principal.
- TValue
O tipo dos elementos da matriz de itens.
Parâmetros
- keys
- TKey[]
O Array unidimensional, com base em zero, que contém as chaves a serem classificadas.
- items
- TValue[]
O Array unidimensional, com base em zero, que contém os itens correspondentes às chaves em keys
ou null
para classificar somente keys
.
- index
- Int32
O índice inicial do intervalo a ser classificado.
- length
- Int32
O número de elementos no intervalo a ser classificado.
Exceções
keys
é null
.
index
é menor que o limite inferior de keys
.
- ou -
length
é menor que zero.
items
não é null
, e o limite inferior de keys
não corresponde ao limite inferior de items
.
- ou -
items
não é null
, e o tamanho de keys
é maior que o tamanho de items
.
- ou -
index
e length
não especificam um intervalo válido no keys
Array.
- ou -
items
não é null
e index
e length
não especificam um intervalo válido no items
Array.
Um ou mais elementos no keys
Array não implementam a interface genérica IComparable<T>.
Exemplos
O exemplo de código a seguir demonstra as sobrecargas de método genérico Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) e Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) para pares de matrizes de classificação que representam chaves e valores.
O exemplo de código define uma comparação alternativa para cadeias de caracteres, chamada ReverseCompare
, que implementa a interface genérica IComparer<string>
(IComparer(Of String)
no Visual Basic, IComparer<String^>
no Visual C++). A comparação chama o método CompareTo(String), invertendo a ordem dos comparandos de modo que as cadeias de caracteres sejam classificadas da maior para a menor, e não o contrário.
O exemplo de código cria e exibe uma matriz de nomes de dinossauros (as chaves) e uma matriz de inteiros que representam o tamanho máximo de cada dinossauro em metros (os valores). Em seguida, as matrizes são classificadas e exibidas várias vezes:
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[]) é usada para classificar ambas as matrizes na ordem dos nomes de dinossauros na primeira matriz.
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) e uma instância de
ReverseCompare
são usadas para inverter a ordem de classificação de matrizes pareadas.A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) é usada para classificar os últimos três elementos de ambas as matrizes.
A sobrecarga de Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) é usada para classificar os três elementos mais recentes de ambas as matrizes na ordem inversa.
Observação
As chamadas para os métodos genéricos não têm diferenças em relação a chamadas para os equivalentes não genéricos, porque o Visual Basic, o C# e o C++ inferem o tipo do parâmetro de tipo genérico do tipo dos dois primeiros argumentos. Se você usar o Ildasm.exe (IL Disassembler) para examinar a MSIL (Linguagem Intermediária da Microsoft), poderá ver que os métodos genéricos estão sendo chamados.
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.
Comentários
Cada chave no keys
Array tem um item correspondente no items
Array. Quando uma chave é reposicionada durante a classificação, o item correspondente no items
Array é reposicionado da mesma forma. Por isso, o items
Array é classificado de acordo com a organização das chaves correspondentes no keys
Array.
Cada chave dentro do intervalo de elementos especificado no keys
Array deve implementar a IComparable<T> interface genérica para ser capaz de comparações com todas as outras chaves.
É possível classificar se há mais itens do que chaves, mas os itens que não tiverem chaves correspondentes não serão classificados. Não será possível classificar se houver mais chaves do que itens; isso lança um ArgumentException.
Caso a classificação não seja concluída com êxito, os resultados são indefinidos.
Esse método usa o algoritmo de classificação introspectiva (introsort) da seguinte maneira:
Se o tamanho da partição for menor ou igual a 16 elementos, ele usará um algoritmo de classificação de inserção .
Se o número de partições exceder 2 * LogN, em que N é o intervalo da matriz de entrada, ele usa um algoritmo Heapsort .
Caso contrário, ele usará um algoritmo Quicksort .
Esta implementação realiza uma classificação instável; ou seja, se dois elementos são iguais, a ordem não deve ser preservada. Por outro lado, uma classificação estável preserva a ordem de elementos iguais.
Esse método é uma operação O(n
log n
), em que n
é length
.
Confira também
- IComparable<T>
- BinarySearch
- Executando operações de cadeia de caracteres Culture-Insensitive em matrizes
Aplica-se a
Comentários
https://aka.ms/ContentUserFeedback.
Em breve: Ao longo de 2024, eliminaremos os problemas do GitHub como o mecanismo de comentários para conteúdo e o substituiremos por um novo sistema de comentários. Para obter mais informações, consulteEnviar e exibir comentários de