Array.Sort Metoda
Definicja
Ważne
Niektóre informacje odnoszą się do produktu w wersji wstępnej, który może zostać znacząco zmodyfikowany przed wydaniem. Firma Microsoft nie udziela żadnych gwarancji, jawnych lub domniemanych, w odniesieniu do informacji podanych w tym miejscu.
Sortuje elementy w tablicy jednowymiarowej.
Przeciążenia
Sort(Array, Array, Int32, Int32, IComparer) |
Sortuje zakres elementów w parze jednowymiarowych Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparerelementu . |
Sort(Array, Int32, Int32, IComparer) |
Sortuje elementy w zakresie elementów jednowymiarowych Array przy użyciu określonego IComparerelementu . |
Sort(Array, Array, Int32, Int32) |
Sortuje zakres elementów w parze jednowymiarowych Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu IComparable implementacji każdego klucza. |
Sort(Array, Int32, Int32) |
Sortuje elementy w zakresie elementów w jednowymiarowym Array przy użyciu IComparable implementacji każdego elementu elementu .Array |
Sort(Array, Array, IComparer) |
Sortuje parę jednowymiarowych Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparerelementu . |
Sort(Array, Array) |
Sortuje parę jednowymiarowych Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszej Array kolejności przy użyciu IComparable implementacji każdego klucza. |
Sort(Array) |
Sortuje elementy w całości jednowymiarowej Array przy użyciu IComparable implementacji każdego elementu obiektu Array. |
Sort(Array, IComparer) |
Sortuje elementy jednowymiarowe Array przy użyciu określonego IComparerelementu . |
Sort<T>(T[]) |
Sortuje elementy w całości Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego elementu elementu .Array |
Sort<T>(T[], IComparer<T>) |
Sortuje elementy w obiekcie Array przy użyciu określonego IComparer<T> interfejsu ogólnego. |
Sort<T>(T[], Comparison<T>) |
Sortuje elementy w obiekcie Array przy użyciu określonego Comparison<T>elementu . |
Sort<T>(T[], Int32, Int32) |
Sortuje elementy w zakresie elementów w obiekcie Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego elementu elementu .Array |
Sort<T>(T[], Int32, Int32, IComparer<T>) |
Sortuje elementy w zakresie elementów w obiekcie Array przy użyciu określonego IComparer<T> interfejsu ogólnego. |
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) |
Sortuje zakres elementów w parze Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparer<T> interfejsu ogólnego. |
Sort<TKey,TValue>(TKey[], TValue[]) |
Sortuje parę Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszej Array kolejności przy użyciu IComparable<T> implementacji interfejsu ogólnego każdego klucza. |
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) |
Sortuje parę Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparer<T> interfejsu ogólnego. |
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) |
Sortuje zakres elementów w parze Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu IComparable<T> implementacji interfejsu ogólnego każdego klucza. |
Sort(Array, Array, Int32, Int32, IComparer)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- 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)
Parametry
- items
- Array
Jednowymiarowy Array element, który zawiera elementy odpowiadające każdemu z kluczy w obiekcie keys
Array.
-lub-
null
aby posortować tylko element keys
Array.
- index
- Int32
Indeks początkowy zakresu do sortowania.
- length
- Int32
Liczba elementów w zakresie do sortowania.
- comparer
- IComparer
Implementacja IComparer do użycia podczas porównywania elementów.
-lub-
null
aby użyć implementacji IComparable każdego elementu.
Wyjątki
keys
to null
.
index
wartość jest mniejsza niż dolna granica .keys
-lub-
Parametr length
ma wartość niższą niż zero.
items
to nie null
, a dolna granica keys
nie jest zgodna z dolną granicą .items
-lub-
items
to nie null
, a długość parametru keys
jest większa niż długość items
.
-lub-
index
i length
nie należy określać prawidłowego zakresu w obiekcie keys
Array.
-lub-
items
parametr nie null
ma wartości i length
index
nie określa prawidłowego zakresu w elemecie items
Array.
-lub-
Implementacja spowodowała comparer
błąd podczas sortowania. Na przykład comparer
może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.
comparer
to null
, a co najmniej jeden element w obiekcie keys
Array nie implementuje interfejsu IComparable .
Przykłady
Poniższy przykład kodu przedstawia sposób sortowania dwóch skojarzonych tablic, w których pierwsza tablica zawiera klucze, a druga tablica zawiera wartości. Sortowania są wykonywane przy użyciu domyślnego modułu porównującego i niestandardowego modułu porównującego, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfoelementu .
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
Uwagi
Każdy klucz w obiekcie keys
ma odpowiedni element w elemencie items
Array.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie items
Array jest podobnie zmieniany. W związku z tym element items
Array jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keys
Array.
Jeśli comparer
parametr ma null
wartość , każdy klucz w określonym zakresie elementów w keys
Array obiekcie musi implementować IComparable interfejs, aby móc porównywać z każdym innym kluczem.
Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; w ten sposób zgłaszany jest błąd ArgumentException.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Platforma .NET zawiera wstępnie zdefiniowane IComparer implementacje wymienione w poniższej tabeli.
Implementacja | Opis |
---|---|
System.Collections.CaseInsensitiveComparer | Porównuje dowolne dwa obiekty, ale wykonuje porównanie bez uwzględniania wielkości liter ciągów. |
Comparer.Default | Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania bieżącej kultury. |
Comparer.DefaultInvariant | Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania niezmiennej kultury. |
Comparer<T>.Default | Porównuje dwa obiekty typu T przy użyciu domyślnej kolejności sortowania typu. |
Można również obsługiwać porównania niestandardowe, podając wystąpienie własnej IComparer implementacji do parametru comparer
. W tym przykładzie zdefiniowano niestandardową IComparer implementację, która odwraca domyślną kolejność sortowania i wykonuje porównanie ciągów bez uwzględniania wielkości liter.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
) , gdzie n
to length
.
Uwagi dotyczące wywoływania
.NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe porównania w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciłArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic z mniejszą lub równą 16 elementami.
Zobacz też
- IComparer
- IComparable
- BinarySearch
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort(Array, Int32, Int32, IComparer)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- 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)
Parametry
- index
- Int32
Indeks początkowy zakresu do sortowania.
- length
- Int32
Liczba elementów w zakresie do sortowania.
- comparer
- IComparer
Implementacja IComparer do użycia podczas porównywania elementów.
-lub-
null
aby użyć implementacji IComparable każdego elementu.
Wyjątki
array
to null
.
Parametr array
jest wielowymiarowy.
index
wartość jest mniejsza niż dolna granica .array
-lub-
Parametr length
ma wartość niższą niż zero.
index
i length
nie należy określać prawidłowego zakresu w pliku array
.
-lub-
Implementacja spowodowała comparer
błąd podczas sortowania. Na przykład comparer
może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.
comparer
to null
, a co najmniej jeden element w elemecie array
nie implementuje interfejsu IComparable .
Przykłady
W poniższym przykładzie kodu pokazano, jak sortować wartości w elemecie Array przy użyciu domyślnego modułu porównującego i niestandardowego porównującego, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfoelementu .
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
Uwagi
Jeśli comparer
parametr ma null
wartość , każdy element w określonym zakresie elementów w array
elemecie musi implementować IComparable interfejs, aby móc porównywać z każdym innym elementem w elemecie array
.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Platforma .NET zawiera wstępnie zdefiniowane IComparer implementacje wymienione w poniższej tabeli.
Implementacja | Opis |
---|---|
System.Collections.CaseInsensitiveComparer | Porównuje dowolne dwa obiekty, ale wykonuje porównanie bez uwzględniania wielkości liter ciągów. |
Comparer.Default | Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania bieżącej kultury. |
Comparer.DefaultInvariant | Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania niezmiennej kultury. |
Comparer<T>.Default | Porównuje dwa obiekty typu T przy użyciu domyślnej kolejności sortowania typu. |
Można również obsługiwać porównania niestandardowe, podając wystąpienie własnej IComparer implementacji do parametru comparer
. W tym przykładzie zdefiniowano klasę, która odwraca domyślną ReverseComparer
kolejność sortowania dla wystąpień typu i wykonuje porównanie ciągów bez uwzględniania wielkości liter.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
) , gdzie n
to length
.
Uwagi dotyczące wywoływania
.NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe porównania w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciłArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic z mniejszą lub równą 16 elementami.
Zobacz też
- IComparer
- IComparable
- BinarySearch
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort(Array, Array, Int32, Int32)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje zakres elementów w parze jednowymiarowych Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu IComparable implementacji każdego klucza.
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)
Parametry
- items
- Array
Jednowymiarowy Array element, który zawiera elementy odpowiadające każdemu z kluczy w obiekcie keys
Array.
-lub-
null
aby posortować tylko element keys
Array.
- index
- Int32
Indeks początkowy zakresu do sortowania.
- length
- Int32
Liczba elementów w zakresie do sortowania.
Wyjątki
keys
to null
.
index
wartość jest mniejsza niż dolna granica .keys
-lub-
Parametr length
ma wartość niższą niż zero.
items
to nie null
, a długość parametru keys
jest większa niż długość items
.
-lub-
index
i length
nie należy określać prawidłowego zakresu w obiekcie keys
Array.
-lub-
items
parametr nie null
ma wartości i length
index
nie określa prawidłowego zakresu w elemecie items
Array.
Co najmniej jeden element w obiekcie keys
Array nie implementuje interfejsu IComparable .
Przykłady
Poniższy przykład kodu przedstawia sposób sortowania dwóch skojarzonych tablic, w których pierwsza tablica zawiera klucze, a druga tablica zawiera wartości. Sortowania są wykonywane przy użyciu domyślnego modułu porównującego i niestandardowego modułu porównującego, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfoelementu .
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
Uwagi
Każdy klucz w obiekcie keys
ma odpowiedni element w elemencie items
Array.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie items
Array jest podobnie zmieniany. W związku z tym element items
Array jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keys
Array.
Każdy klucz w określonym zakresie elementów w keys
Array obiekcie musi implementować IComparable interfejs, aby móc porównywać ze wszystkimi innymi kluczami.
Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; w ten sposób zgłaszany jest błąd ArgumentException.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
) , gdzie n
to length
.
Zobacz też
Dotyczy
Sort(Array, Int32, Int32)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje elementy w zakresie elementów w jednowymiarowym Array przy użyciu IComparable implementacji każdego elementu elementu .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)
Parametry
- index
- Int32
Indeks początkowy zakresu do sortowania.
- length
- Int32
Liczba elementów w zakresie do sortowania.
Wyjątki
array
to null
.
Parametr array
jest wielowymiarowy.
index
wartość jest mniejsza niż dolna granica .array
-lub-
Parametr length
ma wartość niższą niż zero.
index
i length
nie należy określać prawidłowego zakresu w pliku array
.
Co najmniej jeden element w elemecie array
nie implementuje interfejsu IComparable .
Przykłady
W poniższym przykładzie kodu pokazano, jak sortować wartości w elemecie Array przy użyciu domyślnego modułu porównującego i niestandardowego porównującego, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfoelementu .
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
Uwagi
Każdy element w określonym zakresie elementów w array
pliku musi implementować IComparable interfejs, aby móc porównywać z każdym innym elementem w .array
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
) , gdzie n
to length
.
Zobacz też
Dotyczy
Sort(Array, Array, IComparer)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- 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)
Parametry
- items
- Array
Jednowymiarowy Array element, który zawiera elementy odpowiadające każdemu z kluczy w elemecie keys
Array.
-lub-
null
aby posortować tylko keys
Arrayelement .
- comparer
- IComparer
Implementacja IComparer do użycia podczas porównywania elementów.
-lub-
null
aby użyć implementacji IComparable każdego elementu.
Wyjątki
keys
to null
.
items
to nie null
, a długość parametru keys
jest większa niż długość elementu items
.
-lub-
Implementacja błędu spowodowała comparer
błąd podczas sortowania. Na przykład comparer
może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.
comparer
to null
, a co najmniej jeden element w elemecie keys
Array nie implementuje interfejsu IComparable .
Przykłady
W poniższym przykładzie pokazano, jak sortować dwie skojarzone tablice, w których pierwsza tablica zawiera klucze, a druga tablica zawiera wartości. Sortowania są wykonywane przy użyciu domyślnego modułu porównywania i niestandardowego porównywacza, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.
using namespace System;
using namespace System::Collections;
public ref class myReverserClass: public IComparer
{
private:
// Calls CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
}
};
void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
for ( int i = 0; i < myKeys->Length; i++ )
{
Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
}
Console::WriteLine();
}
int main()
{
// Creates and initializes a new Array and a new custom comparer.
array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
IComparer^ myComparer = gcnew myReverserClass;
// Displays the values of the Array.
Console::WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array::Sort( myKeys, myValues, 1, 3 );
Console::WriteLine( "After sorting a section of the Array using the default comparer:" );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, 1, 3, myComparer );
Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array::Sort( myKeys, myValues );
Console::WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, myComparer );
Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
using System;
using System.Collections;
public class SamplesArray {
public class myReverserClass : IComparer {
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare( Object x, Object y ) {
return( (new CaseInsensitiveComparer()).Compare( y, x ) );
}
}
public static void Main() {
// Creates and initializes a new Array and a new custom comparer.
String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
IComparer myComparer = new myReverserClass();
// Displays the values of the Array.
Console.WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array.Sort( myKeys, myValues, 1, 3 );
Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, 1, 3, myComparer );
Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array.Sort( myKeys, myValues );
Console.WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, myComparer );
Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
public static void PrintKeysAndValues( String[] myKeys, String[] myValues ) {
for ( int i = 0; i < myKeys.Length; i++ ) {
Console.WriteLine( " {0,-10}: {1}", myKeys[i], myValues[i] );
}
Console.WriteLine();
}
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
open System
open System.Collections
type MyReverserClass() =
interface IComparer with
member _.Compare(x, y) =
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let printKeysAndValues (myKeys: string []) (myValues: string []) =
for i = 0 to myKeys.Length - 1 do
printfn $" {myKeys[i],-10}: {myValues[i]}"
printfn ""
// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()
// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// This code produces the following output.
// The Array initially contains the following values:
// red : strawberries
// GREEN : PEARS
// YELLOW : LIMES
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the default comparer:
// red : strawberries
// BLUE : BERRIES
// GREEN : PEARS
// YELLOW : LIMES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the reverse case-insensitive comparer:
// red : strawberries
// YELLOW : LIMES
// GREEN : PEARS
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting the entire Array using the default comparer:
// black : olives
// BLUE : BERRIES
// GREEN : PEARS
// orange : cantaloupe
// purple : grapes
// red : strawberries
// YELLOW : LIMES
//
// After sorting the entire Array using the reverse case-insensitive comparer:
// YELLOW : LIMES
// red : strawberries
// purple : grapes
// orange : cantaloupe
// GREEN : PEARS
// BLUE : BERRIES
// black : olives
Imports System.Collections
Public Class SamplesArray
Public Class myReverserClass
Implements IComparer
' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As [Object], y As [Object]) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function 'IComparer.Compare
End Class
Public Shared Sub Main()
' Creates and initializes a new Array and a new custom comparer.
Dim myKeys As [String]() = {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
Dim myValues As [String]() = {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
Dim myComparer = New myReverserClass()
' Displays the values of the Array.
Console.WriteLine("The Array initially contains the following values:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
Console.WriteLine("After sorting a section of the Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
Console.WriteLine("After sorting the entire Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
End Sub
Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])
Dim i As Integer
For i = 0 To myKeys.Length - 1
Console.WriteLine(" {0,-10}: {1}", myKeys(i), myValues(i))
Next i
Console.WriteLine()
End Sub
End Class
'This code produces the following output.
'
'The Array initially contains the following values:
' red : strawberries
' GREEN : PEARS
' YELLOW : LIMES
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the default comparer:
' red : strawberries
' BLUE : BERRIES
' GREEN : PEARS
' YELLOW : LIMES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
' red : strawberries
' YELLOW : LIMES
' GREEN : PEARS
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting the entire Array using the default comparer:
' black : olives
' BLUE : BERRIES
' GREEN : PEARS
' orange : cantaloupe
' purple : grapes
' red : strawberries
' YELLOW : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
' YELLOW : LIMES
' red : strawberries
' purple : grapes
' orange : cantaloupe
' GREEN : PEARS
' BLUE : BERRIES
' black : olives
Uwagi
Każdy klucz w elemencie keys
Array ma odpowiedni element w elemencie items
Array. Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie items
Array jest podobnie zmieniany. W związku z tym element items
jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w elemecie keys
Array.Array
Jeśli comparer
jest to null
, każdy klucz w elemecie keys
Array musi zaimplementować IComparable interfejs, aby móc porównywać z każdym innym kluczem.
Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie elementu ArgumentException.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Platforma .NET zawiera wstępnie zdefiniowane IComparer implementacje wymienione w poniższej tabeli.
Implementacja | Opis |
---|---|
System.Collections.CaseInsensitiveComparer | Porównuje wszystkie dwa obiekty, ale wykonuje porównanie bez uwzględniania wielkości liter ciągów. |
Comparer.Default | Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania bieżącej kultury. |
Comparer.DefaultInvariant | Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania niezmiennej kultury. |
Comparer<T>.Default | Porównuje dwa obiekty typu T przy użyciu domyślnej kolejności sortowania typu. |
Możesz również obsługiwać porównania niestandardowe, podając wystąpienie własnej IComparer implementacji do parametru comparer
. W tym przykładzie zdefiniowano implementację, która odwraca domyślną IComparer kolejność sortowania i wykonuje porównanie ciągów bez uwzględniania wielkości liter.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
), gdzie n
jest Length .keys
Uwagi dotyczące wywoływania
.NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do wywołującego. Począwszy od .NET Framework 4.5, możliwe jest, że operacje sortowania, które wcześniej rzuciłyArgumentException, nie będą zgłaszać wyjątku, ponieważ algorytmy sortowania wstawiania i heapsort nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.
Zobacz też
- IComparer
- IComparable
- BinarySearch
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort(Array, Array)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje parę obiektów jednowymiarowych Array (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszej Array kolejności przy użyciu IComparable implementacji każdego klucza.
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)
Parametry
- items
- Array
Jednowymiarowy Array element, który zawiera elementy odpowiadające każdemu z kluczy w elemecie keys
Array.
-lub-
null
aby posortować tylko keys
Arrayelement .
Wyjątki
keys
to null
.
items
to nie null
, a długość parametru keys
jest większa niż długość elementu items
.
Co najmniej jeden element w elemecie keys
Array nie implementuje interfejsu IComparable .
Przykłady
W poniższym przykładzie pokazano, jak sortować dwie skojarzone tablice, w których pierwsza tablica zawiera klucze, a druga tablica zawiera wartości. Sortowania są wykonywane przy użyciu domyślnego modułu porównywania i niestandardowego porównywacza, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.
using namespace System;
using namespace System::Collections;
public ref class myReverserClass: public IComparer
{
private:
// Calls CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
}
};
void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
for ( int i = 0; i < myKeys->Length; i++ )
{
Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
}
Console::WriteLine();
}
int main()
{
// Creates and initializes a new Array and a new custom comparer.
array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
IComparer^ myComparer = gcnew myReverserClass;
// Displays the values of the Array.
Console::WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array::Sort( myKeys, myValues, 1, 3 );
Console::WriteLine( "After sorting a section of the Array using the default comparer:" );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, 1, 3, myComparer );
Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array::Sort( myKeys, myValues );
Console::WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, myComparer );
Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
using System;
using System.Collections;
public class SamplesArray {
public class myReverserClass : IComparer {
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare( Object x, Object y ) {
return( (new CaseInsensitiveComparer()).Compare( y, x ) );
}
}
public static void Main() {
// Creates and initializes a new Array and a new custom comparer.
String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
IComparer myComparer = new myReverserClass();
// Displays the values of the Array.
Console.WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array.Sort( myKeys, myValues, 1, 3 );
Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, 1, 3, myComparer );
Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array.Sort( myKeys, myValues );
Console.WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, myComparer );
Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
public static void PrintKeysAndValues( String[] myKeys, String[] myValues ) {
for ( int i = 0; i < myKeys.Length; i++ ) {
Console.WriteLine( " {0,-10}: {1}", myKeys[i], myValues[i] );
}
Console.WriteLine();
}
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
open System
open System.Collections
type MyReverserClass() =
interface IComparer with
member _.Compare(x, y) =
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let printKeysAndValues (myKeys: string []) (myValues: string []) =
for i = 0 to myKeys.Length - 1 do
printfn $" {myKeys[i],-10}: {myValues[i]}"
printfn ""
// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()
// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// This code produces the following output.
// The Array initially contains the following values:
// red : strawberries
// GREEN : PEARS
// YELLOW : LIMES
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the default comparer:
// red : strawberries
// BLUE : BERRIES
// GREEN : PEARS
// YELLOW : LIMES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the reverse case-insensitive comparer:
// red : strawberries
// YELLOW : LIMES
// GREEN : PEARS
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting the entire Array using the default comparer:
// black : olives
// BLUE : BERRIES
// GREEN : PEARS
// orange : cantaloupe
// purple : grapes
// red : strawberries
// YELLOW : LIMES
//
// After sorting the entire Array using the reverse case-insensitive comparer:
// YELLOW : LIMES
// red : strawberries
// purple : grapes
// orange : cantaloupe
// GREEN : PEARS
// BLUE : BERRIES
// black : olives
Imports System.Collections
Public Class SamplesArray
Public Class myReverserClass
Implements IComparer
' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As [Object], y As [Object]) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function 'IComparer.Compare
End Class
Public Shared Sub Main()
' Creates and initializes a new Array and a new custom comparer.
Dim myKeys As [String]() = {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
Dim myValues As [String]() = {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
Dim myComparer = New myReverserClass()
' Displays the values of the Array.
Console.WriteLine("The Array initially contains the following values:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
Console.WriteLine("After sorting a section of the Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
Console.WriteLine("After sorting the entire Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
End Sub
Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])
Dim i As Integer
For i = 0 To myKeys.Length - 1
Console.WriteLine(" {0,-10}: {1}", myKeys(i), myValues(i))
Next i
Console.WriteLine()
End Sub
End Class
'This code produces the following output.
'
'The Array initially contains the following values:
' red : strawberries
' GREEN : PEARS
' YELLOW : LIMES
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the default comparer:
' red : strawberries
' BLUE : BERRIES
' GREEN : PEARS
' YELLOW : LIMES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
' red : strawberries
' YELLOW : LIMES
' GREEN : PEARS
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting the entire Array using the default comparer:
' black : olives
' BLUE : BERRIES
' GREEN : PEARS
' orange : cantaloupe
' purple : grapes
' red : strawberries
' YELLOW : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
' YELLOW : LIMES
' red : strawberries
' purple : grapes
' orange : cantaloupe
' GREEN : PEARS
' BLUE : BERRIES
' black : olives
Uwagi
Każdy klucz w elemencie keys
Array ma odpowiedni element w elemencie items
Array. Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie items
Array jest podobnie zmieniany. W związku z tym element items
jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w elemecie keys
Array.Array
Każdy klucz w elemecie keys
Array musi zaimplementować IComparable interfejs, aby był w stanie porównać każdy inny klucz.
Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie elementu ArgumentException.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
), gdzie n
jest Length .keys
Zobacz też
- IComparable
- BinarySearch
- IDictionary
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort(Array)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje elementy w całości jednowymiarowej Array przy użyciu IComparable implementacji każdego elementu klasy 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)
Parametry
Wyjątki
array
to null
.
Parametr array
jest wielowymiarowy.
Co najmniej jeden element w programie array
nie implementuje interfejsu IComparable .
Przykłady
W poniższym przykładzie kodu pokazano, jak sortować wartości przy użyciu domyślnego Array porównania i niestandardowego porównywacza, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.
using namespace System;
using namespace System::Collections;
public ref class ReverseComparer : IComparer
{
public:
// Call CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
}
};
void DisplayValues(array<String^>^ arr)
{
for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
Console::WriteLine( " [{0}] : {1}", i, arr[ i ] );
Console::WriteLine();
}
int main()
{
// Create and initialize a new array. and a new custom comparer.
array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
"over","the","lazy","dog" };
// Instantiate the reverse comparer.
IComparer^ revComparer = gcnew ReverseComparer();
// Display the values of the Array.
Console::WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array::Sort(words, 1, 3);
Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array::Sort(words, 1, 3, revComparer);
Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array::Sort(words);
Console::WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array::Sort(words, revComparer);
Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
/*
This code produces the following output.
The Array initially contains the following values:
[0] : The
[1] : QUICK
[2] : BROWN
[3] : FOX
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the default comparer:
[0] : The
[1] : BROWN
[2] : FOX
[3] : QUICK
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the reverse case-insensitive comparer:
[0] : The
[1] : QUICK
[2] : FOX
[3] : BROWN
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting the entire Array using the default comparer:
[0] : BROWN
[1] : dog
[2] : FOX
[3] : jumps
[4] : lazy
[5] : over
[6] : QUICK
[7] : the
[8] : The
After sorting the entire Array using the reverse case-insensitive comparer:
[0] : the
[1] : The
[2] : QUICK
[3] : over
[4] : lazy
[5] : jumps
[6] : FOX
[7] : dog
[8] : BROWN
*/
using System;
using System.Collections;
public class ReverseComparer : IComparer
{
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
public int Compare(Object x, Object y)
{
return (new CaseInsensitiveComparer()).Compare(y, x );
}
}
public class Example
{
public static void Main()
{
// Create and initialize a new array.
String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" };
// Instantiate the reverse comparer.
IComparer revComparer = new ReverseComparer();
// Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3);
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer);
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array.Sort(words);
Console.WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer);
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
public static void DisplayValues(String[] arr)
{
for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
i++ ) {
Console.WriteLine( " [{0}] : {1}", i, arr[i] );
}
Console.WriteLine();
}
}
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
open System
open System.Collections
type ReverseComparer() =
interface IComparer with
member _.Compare(x, y) =
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let displayValues (arr: string []) =
for i = 0 to arr.Length - 1 do
printfn $" [{i}] : {arr[i]}"
printfn ""
// Create and initialize a new array.
let words =
[| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
"over"; "the"; "lazy"; "dog" |]
// Instantiate the reverse comparer.
let revComparer = ReverseComparer()
// Display the values of the array.
printfn "The original order of elements in the array:"
displayValues words
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
printfn "After sorting elements 1-3 by using the default comparer:"
displayValues words
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
printfn "After sorting elements 1-3 by using the reverse case-insensitive comparer:"
displayValues words
// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
Imports System.Collections
Public Class ReverseComparer : Implements IComparer
' Call CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As Object, y As Object) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function
End Class
Public Module Example
Public Sub Main()
' Create and initialize a new array.
Dim words() As String = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" }
' Instantiate a new custom comparer.
Dim revComparer As New ReverseComparer()
' Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" )
DisplayValues(words)
' Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:")
DisplayValues(words)
' Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:")
DisplayValues(words)
' Sort the entire array using the default comparer.
Array.Sort(words)
Console.WriteLine( "After sorting the entire array by using the default comparer:")
DisplayValues(words)
' Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:")
DisplayValues(words)
End Sub
Public Sub DisplayValues(arr() As String)
For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
Console.WriteLine(" [{0}] : {1}", i, arr(i))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' The original order of elements in the array:
' [0] : The
' [1] : QUICK
' [2] : BROWN
' [3] : FOX
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the default comparer:
' [0] : The
' [1] : BROWN
' [2] : FOX
' [3] : QUICK
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the reverse case-insensitive comparer:
' [0] : The
' [1] : QUICK
' [2] : FOX
' [3] : BROWN
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting the entire array by using the default comparer:
' [0] : BROWN
' [1] : dog
' [2] : FOX
' [3] : jumps
' [4] : lazy
' [5] : over
' [6] : QUICK
' [7] : the
' [8] : The
'
' After sorting the entire array using the reverse case-insensitive comparer:
' [0] : the
' [1] : The
' [2] : QUICK
' [3] : over
' [4] : lazy
' [5] : jumps
' [6] : FOX
' [7] : dog
' [8] : BROWN
Uwagi
Każdy element array
musi zaimplementować IComparable interfejs, aby móc porównywać z każdym innym elementem w elemecie array
.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
), gdzie n
jest Length .array
Zobacz też
Dotyczy
Sort(Array, IComparer)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- 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)
Parametry
- array
- Array
Jednowymiarowa tablica do sortowania.
- comparer
- IComparer
Implementacja do użycia podczas porównywania elementów.
-lub-
null
aby użyć implementacji IComparable każdego elementu.
Wyjątki
array
to null
.
Parametr array
jest wielowymiarowy.
comparer
to null
, a co najmniej jeden element w elemecie array
nie implementuje interfejsu IComparable .
Implementacja spowodowała comparer
błąd podczas sortowania. Na przykład comparer
może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.
Przykłady
Poniższy przykład sortuje wartości w tablicy ciągów przy użyciu domyślnego porównywacza. Definiuje również niestandardową IComparer implementację o nazwie ReverseComparer
, która odwraca domyślną kolejność sortowania obiektu podczas porównywania ciągu bez uwzględniania wielkości liter. Należy pamiętać, że dane wyjściowe mogą się różnić w zależności od bieżącej kultury.
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
Uwagi
Jeśli comparer
element ma null
wartość , każdy element array
musi implementować interfejs, IComparable aby móc porównywać z każdym innym elementem w elemecie array
.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log ) , gdzie n
jest typu Lengtharray
.n
Platforma .NET zawiera wstępnie zdefiniowane IComparer implementacje wymienione w poniższej tabeli.
Implementacja | Opis |
---|---|
System.Collections.CaseInsensitiveComparer | Porównuje dowolne dwa obiekty, ale wykonuje porównanie bez uwzględniania wielkości liter ciągów. |
Comparer.Default | Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania bieżącej kultury. |
Comparer.DefaultInvariant | Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania niezmiennej kultury. |
Comparer<T>.Default | Porównuje dwa obiekty typu T przy użyciu domyślnej kolejności sortowania typu. |
Można również obsługiwać porównania niestandardowe, podając wystąpienie własnej IComparer implementacji do parametru comparer
. W tym przykładzie zdefiniowano klasę, która odwraca domyślną ReverseComparer
kolejność sortowania dla wystąpień typu i wykonuje porównanie ciągów bez uwzględniania wielkości liter.
Uwagi dotyczące wywoływania
.NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do wywołującego. Począwszy od .NET Framework 4.5, możliwe jest, że operacje sortowania, które wcześniej rzuciłyArgumentException, nie będą zgłaszać wyjątku, ponieważ algorytmy sortowania wstawiania i heapsort nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.
Zobacz też
- IComparer
- IComparable
- BinarySearch
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort<T>(T[])
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje elementy w całości Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego elementu elementu .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())
Parametry typu
- T
Typ elementów tablicy.
Parametry
- array
- T[]
Jednowymiarowy, oparty na Array zerach do sortowania.
Wyjątki
array
to null
.
Co najmniej jeden element w elemecie array
nie implementuje interfejsu IComparable<T> ogólnego.
Przykłady
Poniższy przykład kodu przedstawia Sort<T>(T[]) przeciążenie metody ogólnej i BinarySearch<T>(T[], T) przeciążenie metody ogólnej. Tablica ciągów jest tworzona w żadnej określonej kolejności.
Tablica jest wyświetlana, sortowana i ponownie wyświetlana.
Uwaga
Wywołania Sort metod ogólnych i BinarySearch nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ język Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszego argumentu. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka pośredniego firmy Microsoft (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.
Przeciążenie BinarySearch<T>(T[], T) metody ogólnej jest następnie używane do wyszukiwania dwóch ciągów, jeden, który nie znajduje się w tablicy i jeden, który jest. Tablica i wartość BinarySearch zwracana metody są przekazywane do ShowWhere
metody ogólnej, która wyświetla wartość indeksu, jeśli ciąg zostanie znaleziony, a w przeciwnym razie elementy, między którymi znajduje się ciąg wyszukiwania, gdyby znajdowały się w tablicy. Indeks jest ujemny, jeśli ciąg nie jest n tablicy, więc ShowWhere
metoda przyjmuje bitowe uzupełnienie (operator ~ w języku C# i Visual C++, Xor
-1 w Visual Basic), aby uzyskać indeks pierwszego elementu na liście, który jest większy niż ciąg wyszukiwania.
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.
Uwagi
Każdy element array
musi implementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym elementem w elemecie array
.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log ) , gdzie n
jest typu Lengtharray
.n
Zobacz też
Dotyczy
Sort<T>(T[], IComparer<T>)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje elementy w obiekcie Array przy użyciu określonego IComparer<T> interfejsu ogólnego.
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))
Parametry typu
- T
Typ elementów tablicy.
Parametry
- array
- T[]
Jednowymiarowa, zero-bazowa Array do sortowania.
- comparer
- IComparer<T>
Implementacja interfejsu IComparer<T> ogólnego do użycia podczas porównywania elementów lub null
do użycia implementacji interfejsu IComparable<T> ogólnego każdego elementu.
Wyjątki
array
to null
.
comparer
to null
, a co najmniej jeden element w elemecie array
nie implementuje interfejsu IComparable<T> ogólnego.
Implementacja spowodowała comparer
błąd podczas sortowania. Na przykład comparer
może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.
Przykłady
Poniższy przykład kodu przedstawia Sort<T>(T[], IComparer<T>) przeciążenie metody ogólnej i BinarySearch<T>(T[], T, IComparer<T>) przeciążenie metody ogólnej.
W przykładzie kodu zdefiniowano alternatywny moduł porównujący ciągów o nazwie ReverseCompare
, który implementuje IComparer<string>
interfejs ogólny (IComparer(Of String)
w języku Visual Basic IComparer<String^>
w języku Visual C++). Funkcja porównująca wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzań, tak aby ciągi sortowane były w sposób wysoki do niski, a nie z niskimi do wysokich.
Tablica jest wyświetlana, sortowana i ponownie wyświetlana. Tablice muszą być sortowane w celu użycia BinarySearch metody .
Uwaga
Wywołania Sort<T>(T[], IComparer<T>) metod ogólnych i BinarySearch<T>(T[], T, IComparer<T>) nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ język Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszego argumentu. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka pośredniego firmy Microsoft (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.
Przeciążenie BinarySearch<T>(T[], T, IComparer<T>) metody ogólnej jest następnie używane do wyszukiwania dwóch ciągów, jeden, który nie znajduje się w tablicy i jeden, który jest. Tablica i wartość BinarySearch<T>(T[], T, IComparer<T>) zwracana metody są przekazywane do ShowWhere
metody ogólnej, która wyświetla wartość indeksu, jeśli ciąg zostanie znaleziony, a w przeciwnym razie elementy, między którymi znajduje się ciąg wyszukiwania, gdyby znajdowały się w tablicy. Indeks jest ujemny, jeśli ciąg nie jest n tablicy, więc ShowWhere
metoda przyjmuje bitowe uzupełnienie (operator ~ w języku C# i Visual C++, Xor
-1 w Visual Basic), aby uzyskać indeks pierwszego elementu na liście, który jest większy niż ciąg wyszukiwania.
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.
Uwagi
Jeśli comparer
element ma null
wartość , każdy element array
musi implementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym elementem w .array
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log ) , gdzie n
jest typu Lengtharray
.n
Uwagi dotyczące wywoływania
.NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe porównania w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciłArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic z mniejszą lub równą 16 elementami.
Zobacz też
- IComparer<T>
- IComparable<T>
- BinarySearch
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort<T>(T[], Comparison<T>)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje elementy w obiekcie Array przy użyciu określonego Comparison<T>elementu .
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))
Parametry typu
- T
Typ elementów tablicy.
Parametry
- array
- T[]
Jednowymiarowy, oparty na Array zerach do sortowania.
- comparison
- Comparison<T>
Element Comparison<T> do użycia podczas porównywania elementów.
Wyjątki
Implementacja spowodowała comparison
błąd podczas sortowania. Na przykład comparison
może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.
Przykłady
W poniższym przykładzie kodu pokazano Sort(Comparison<T>) przeciążenie metody.
W przykładzie kodu zdefiniowano alternatywną metodę porównania ciągów o nazwie CompareDinosByLength
. Ta metoda działa w następujący sposób: Po pierwsze, comparands są testowane podnull
kątem, a odwołanie o wartości null jest traktowane jako mniejsze niż nie null. Po drugie, długości ciągów są porównywane, a dłuższy ciąg jest uznawany za większy. Po trzecie, jeśli długości są równe, używane jest zwykłe porównanie ciągów.
Tablica ciągów jest tworzona i wypełniana czterema ciągami bez określonej kolejności. Lista zawiera również pusty ciąg i odwołanie o wartości null. Zostanie wyświetlona lista posortowana przy użyciu delegata ogólnego reprezentującego Comparison<T> metodę i wyświetlona CompareDinosByLength
ponownie.
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"
Uwagi
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log ) , gdzie n
jest typu Lengtharray
.n
Uwagi dotyczące wywoływania
.NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe porównania w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciłArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic z mniejszą lub równą 6 elementami.
Zobacz też
Dotyczy
Sort<T>(T[], Int32, Int32)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje elementy w zakresie elementów w obiekcie Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego elementu elementu .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)
Parametry typu
- T
Typ elementów tablicy.
Parametry
- array
- T[]
Jednowymiarowy, oparty na Array zerach do sortowania.
- index
- Int32
Indeks początkowy zakresu do sortowania.
- length
- Int32
Liczba elementów w zakresie do sortowania.
Wyjątki
array
to null
.
index
wartość jest mniejsza niż dolna granica .array
-lub-
Parametr length
ma wartość niższą niż zero.
index
i length
nie należy określać prawidłowego zakresu w pliku array
.
Co najmniej jeden element w elemecie array
nie implementuje interfejsu IComparable<T> ogólnego.
Przykłady
Poniższy przykład kodu przedstawia Sort<T>(T[], Int32, Int32) przeciążenie metody ogólnej i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) przeciążenie metody ogólnej do sortowania zakresu w tablicy.
W przykładzie kodu zdefiniowano alternatywny moduł porównujący ciągów o nazwie ReverseCompare
, który implementuje IComparer<string>
interfejs ogólny (IComparer(Of String)
w języku Visual Basic IComparer<String^>
w języku Visual C++). Funkcja porównująca wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzań, tak aby ciągi sortowane były w sposób wysoki do niski, a nie z niskimi do wysokich.
Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów, składającą się z trzech roślinożernych, po których następują trzy mięsożerne (tyrannosauridy, aby być precyzyjnym). Przeciążenie Sort<T>(T[], Int32, Int32) metody ogólnej służy do sortowania trzech ostatnich elementów tablicy, które są następnie wyświetlane. Przeciążenie Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) metody ogólnej służy ReverseCompare
do sortowania ostatnich trzech elementów w odwrotnej kolejności. Dokładnie zdezorientowane dinozaury są ponownie wyświetlane.
Uwaga
Wywołania Sort<T>(T[], IComparer<T>) metod ogólnych i BinarySearch<T>(T[], T, IComparer<T>) nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ język Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszego argumentu. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka pośredniego firmy Microsoft (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.
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
Uwagi
Każdy element w określonym zakresie elementów w array
musi implementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym elementem w elemecie array
.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
) , gdzie n
to length
.
Zobacz też
Dotyczy
Sort<T>(T[], Int32, Int32, IComparer<T>)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje elementy w zakresie elementów w obiekcie Array przy użyciu określonego IComparer<T> interfejsu ogólnego.
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))
Parametry typu
- T
Typ elementów tablicy.
Parametry
- array
- T[]
Jednowymiarowy, oparty na Array zerach do sortowania.
- index
- Int32
Indeks początkowy zakresu do sortowania.
- length
- Int32
Liczba elementów w zakresie do sortowania.
- comparer
- IComparer<T>
Implementacja interfejsu IComparer<T> ogólnego do użycia podczas porównywania elementów lub null
do użycia implementacji interfejsu IComparable<T> ogólnego każdego elementu.
Wyjątki
array
to null
.
index
wartość jest mniejsza niż dolna granica .array
-lub-
Parametr length
ma wartość niższą niż zero.
index
i length
nie należy określać prawidłowego zakresu w pliku array
.
-lub-
Implementacja spowodowała comparer
błąd podczas sortowania. Na przykład comparer
może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.
comparer
to null
, a co najmniej jeden element w elemecie array
nie implementuje interfejsu IComparable<T> ogólnego.
Przykłady
Poniższy przykład kodu przedstawia Sort<T>(T[], Int32, Int32) przeciążenie metody ogólnej i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) przeciążenie metody ogólnej do sortowania zakresu w tablicy.
W przykładzie kodu zdefiniowano alternatywny moduł porównujący ciągów o nazwie ReverseCompare
, który implementuje IComparer<string>
interfejs ogólny (IComparer(Of String)
w języku Visual Basic IComparer<String^>
w języku Visual C++). Funkcja porównująca wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzań, tak aby ciągi sortowane były w sposób wysoki do niski, a nie z niskimi do wysokich.
Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów, składającą się z trzech roślinożernych, po których następują trzy mięsożerne (tyrannosauridy, aby być precyzyjnym). Przeciążenie Sort<T>(T[], Int32, Int32) metody ogólnej służy do sortowania trzech ostatnich elementów tablicy, które są następnie wyświetlane. Przeciążenie Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) metody ogólnej służy ReverseCompare
do sortowania ostatnich trzech elementów w odwrotnej kolejności. Dokładnie zdezorientowane dinozaury są ponownie wyświetlane.
Uwaga
Wywołania Sort<T>(T[], IComparer<T>) metod ogólnych i BinarySearch<T>(T[], T, IComparer<T>) nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ język Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszego argumentu. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka pośredniego firmy Microsoft (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.
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
Uwagi
Jeśli comparer
parametr ma null
wartość , każdy element w określonym zakresie elementów w array
elemecie musi implementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym elementem w elemecie array
.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
) , gdzie n
to length
.
Uwagi dotyczące wywoływania
.NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe porównania w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciłArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic z mniejszą lub równą 16 elementami.
Zobacz też
- IComparer<T>
- IComparable<T>
- BinarySearch
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje zakres elementów w parze Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparer<T> interfejsu ogólnego.
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))
Parametry typu
- TKey
Typ elementów tablicy kluczy.
- TValue
Typ elementów tablicy elementów.
Parametry
- keys
- TKey[]
Jednowymiarowa, zero Array oparta na kluczach do sortowania.
- items
- TValue[]
Jednowymiarowa, zero Array oparta na elementach, które odpowiadają kluczom w keys
obiekcie lub null
sortowaniu tylko keys
.
- index
- Int32
Indeks początkowy zakresu do sortowania.
- length
- Int32
Liczba elementów w zakresie do sortowania.
- comparer
- IComparer<TKey>
Implementacja interfejsu IComparer<T> ogólnego do użycia podczas porównywania elementów lub null
do użycia implementacji interfejsu IComparable<T> ogólnego każdego elementu.
Wyjątki
keys
to null
.
index
wartość jest mniejsza niż dolna granica .keys
-lub-
Parametr length
ma wartość niższą niż zero.
items
to nie null
, a dolna granica keys
nie jest zgodna z dolną granicą .items
-lub-
items
to nie null
, a długość parametru keys
jest większa niż długość items
.
-lub-
index
i length
nie należy określać prawidłowego zakresu w obiekcie keys
Array.
-lub-
items
parametr nie null
ma wartości i length
index
nie określa prawidłowego zakresu w elemecie items
Array.
-lub-
Implementacja spowodowała comparer
błąd podczas sortowania. Na przykład comparer
może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.
comparer
to null
, a co najmniej jeden element w obiekcie keys
Array nie implementuje interfejsu IComparable<T> ogólnego.
Przykłady
W poniższym przykładzie kodu pokazano Sort<TKey,TValue>(TKey[], TValue[])przeciążenia metody , , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ogólnej dla sortowania par tablic reprezentujących klucze i wartości.
W przykładzie kodu zdefiniowano alternatywny moduł porównujący ciągów o nazwie ReverseCompare
, który implementuje IComparer<string>
interfejs ogólny (IComparer(Of String)
w języku Visual Basic IComparer<String^>
w języku Visual C++). Funkcja porównująca wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzań, tak aby ciągi sortowane były w sposób wysoki do niski, a nie z niskimi do wysokich.
Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów (kluczy) oraz tablicę liczb całkowitych reprezentujących maksymalną długość każdego dinozaura w metrach (wartości). Tablice są następnie sortowane i wyświetlane kilka razy:
Przeciążenie Sort<TKey,TValue>(TKey[], TValue[]) służy do sortowania obu tablic w kolejności nazw dinozaurów w pierwszej tablicy.
Przeciążenie Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) i wystąpienie
ReverseCompare
klasy są używane do odwrócenia kolejności sortowania sparowanych tablic.Przeciążenie służy do sortowania Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) trzech ostatnich elementów obu tablic.
Przeciążenie służy do sortowania Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) trzech ostatnich elementów obu tablic w odwrotnej kolejności.
Uwaga
Wywołania metod ogólnych nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ język Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu dwóch pierwszych argumentów. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka pośredniego firmy Microsoft (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.
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.
Uwagi
Każdy klucz w obiekcie keys
ma odpowiedni element w elemencie items
Array.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie items
Array jest podobnie zmieniany. W związku z tym element items
Array jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keys
Array.
Jeśli comparer
parametr ma null
wartość , każdy klucz w określonym zakresie elementów w keys
Array obiekcie musi implementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym kluczem.
Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; w ten sposób zgłaszany jest błąd ArgumentException.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspektywnego w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
) , gdzie n
to length
.
Uwagi dotyczące wywoływania
.NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe porównania w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciłArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic z mniejszą lub równą 16 elementami.
Zobacz też
- IComparer<T>
- IComparable<T>
- BinarySearch
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort<TKey,TValue>(TKey[], TValue[])
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje parę Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszej Array kolejności przy użyciu IComparable<T> implementacji interfejsu ogólnego każdego klucza.
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())
Parametry typu
- TKey
Typ elementów tablicy kluczy.
- TValue
Typ elementów tablicy elementów.
Parametry
- keys
- TKey[]
Jednowymiarowa, zero Array oparta na kluczach do sortowania.
- items
- TValue[]
Jednowymiarowa, zero Array oparta na elementach, które odpowiadają kluczom w keys
obiekcie lub null
sortowaniu tylko keys
.
Wyjątki
keys
to null
.
items
to nie null
, a dolna granica keys
nie jest zgodna z dolną granicą .items
-lub-
items
to nie null
, a długość parametru keys
jest większa niż długość items
.
Co najmniej jeden element w obiekcie keys
Array nie implementuje interfejsu IComparable<T> ogólnego.
Przykłady
W poniższym przykładzie kodu pokazano Sort<TKey,TValue>(TKey[], TValue[])przeciążenia metody , , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ogólnej dla sortowania par tablic reprezentujących klucze i wartości.
W przykładzie kodu zdefiniowano alternatywny moduł porównujący ciągów o nazwie ReverseCompare
, który implementuje IComparer<string>
interfejs ogólny (IComparer(Of String)
w języku Visual Basic IComparer<String^>
w języku Visual C++). Funkcja porównująca wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzań, tak aby ciągi sortowane były w sposób wysoki do niski, a nie z niskimi do wysokich.
Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów (kluczy) oraz tablicę liczb całkowitych reprezentujących maksymalną długość każdego dinozaura w metrach (wartości). Tablice są następnie sortowane i wyświetlane kilka razy:
Przeciążenie Sort<TKey,TValue>(TKey[], TValue[]) służy do sortowania obu tablic w kolejności nazw dinozaurów w pierwszej tablicy.
Przeciążenie Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) i wystąpienie
ReverseCompare
klasy są używane do odwrócenia kolejności sortowania sparowanych tablic.Przeciążenie służy do sortowania Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) trzech ostatnich elementów obu tablic.
Przeciążenie służy do sortowania Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) trzech ostatnich elementów obu tablic w odwrotnej kolejności.
Uwaga
Wywołania metod ogólnych nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ język Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu dwóch pierwszych argumentów. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka pośredniego firmy Microsoft (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.
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.
Uwagi
Każdy klucz w obiekcie keys
ma odpowiedni element w elemencie items
Array.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie items
Array jest podobnie zmieniany. W związku z tym element items
Array jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keys
Array.
Każdy klucz w pliku keys
Array musi implementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym kluczem.
Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; w ten sposób zgłaszany jest błąd ArgumentException.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsortowego) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu Heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log ) , gdzie n
jest typu Lengtharray
.n
Zobacz też
- IComparable<T>
- BinarySearch
- IDictionary<TKey,TValue>
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje parę Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparer<T> interfejsu ogólnego.
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))
Parametry typu
- TKey
Typ elementów tablicy kluczy.
- TValue
Typ elementów tablicy elementów.
Parametry
- keys
- TKey[]
Jednowymiarowy, zero oparty Array na kluczu, który zawiera klucze do sortowania.
- items
- TValue[]
Jednowymiarowy, zero oparty Array na elementach, który zawiera elementy odpowiadające kluczom w keys
obiekcie lub null
sortowanie tylko keys
.
- comparer
- IComparer<TKey>
Implementacja IComparer<T> interfejsu ogólnego do użycia podczas porównywania elementów lub null
użycia IComparable<T> ogólnej implementacji interfejsu każdego elementu.
Wyjątki
keys
to null
.
items
to nie null
, a dolna granica keys
nie jest zgodna z dolną granicą .items
-lub-
items
to nie null
, a długość parametru keys
jest większa niż długość items
.
-lub-
Implementacja spowodowała comparer
błąd podczas sortowania. Na przykład comparer
może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.
comparer
to null
, a co najmniej jeden element w obiekcie keys
Array nie implementuje interfejsu IComparable<T> ogólnego.
Przykłady
W poniższym przykładzie kodu pokazano Sort<TKey,TValue>(TKey[], TValue[])przeciążenia metody , [], Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ogólnej dla sortowania par tablic reprezentujących klucze i wartości.
W przykładzie kodu zdefiniowano alternatywny moduł porównujący ciągów o nazwie ReverseCompare
, który implementuje IComparer<string>
interfejs ogólny (IComparer(Of String)
w języku Visual Basic IComparer<String^>
w języku Visual C++). Funkcja porównująca wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzań, tak aby ciągi sortowane były w sposób wysoki do niski, a nie z niskimi do wysokich.
Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów (kluczy) oraz tablicę liczb całkowitych reprezentujących maksymalną długość każdego dinozaura w metrach (wartości). Tablice są następnie sortowane i wyświetlane kilka razy:
Przeciążenie Sort<TKey,TValue>(TKey[], TValue[]) służy do sortowania obu tablic w kolejności nazw dinozaurów w pierwszej tablicy.
Przeciążenie Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) i wystąpienie
ReverseCompare
klasy są używane do odwrócenia kolejności sortowania sparowanych tablic.Przeciążenie służy do sortowania Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) trzech ostatnich elementów obu tablic.
Przeciążenie służy do sortowania Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) trzech ostatnich elementów obu tablic w odwrotnej kolejności.
Uwaga
Wywołania metod ogólnych nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ język Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu dwóch pierwszych argumentów. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka pośredniego firmy Microsoft (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.
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.
Uwagi
Każdy klucz w elemencie keys
Array ma odpowiedni element w elemencie items
Array. Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie items
Array jest podobnie zmieniany. W związku z tym element items
jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w elemecie keys
Array.Array
Jeśli comparer
jest to null
, każdy klucz w elemecie keys
Array musi zaimplementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym kluczem.
Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie elementu ArgumentException.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
), gdzie n
jest Length .array
Uwagi dotyczące wywoływania
.NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe porównania w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciłArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic z mniejszą lub równą 16 elementami.
Zobacz też
- IComparer<T>
- IComparable<T>
- BinarySearch
- Wykonywanie niezależnych od kultury operacji na ciągach w tablicach
Dotyczy
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)
- Źródło:
- Array.cs
- Źródło:
- Array.cs
- Źródło:
- Array.cs
Sortuje zakres elementów w parze Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszej Array kolejności przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego klucza.
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)
Parametry typu
- TKey
Typ elementów tablicy kluczy.
- TValue
Typ elementów tablicy elementów.
Parametry
- keys
- TKey[]
Jednowymiarowy, zero oparty Array na kluczu, który zawiera klucze do sortowania.
- items
- TValue[]
Jednowymiarowy, zero oparty Array na elementach, który zawiera elementy odpowiadające kluczom w keys
obiekcie lub null
sortowanie tylko keys
.
- index
- Int32
Początkowy indeks zakresu do sortowania.
- length
- Int32
Liczba elementów w zakresie do sortowania.
Wyjątki
keys
to null
.
index
jest mniejsza niż niższa granica .keys
-lub-
Parametr length
ma wartość niższą niż zero.
items
nie null
jest , a dolna granica keys
nie jest zgodna z dolną granicą .items
-lub-
items
to nie null
, a długość parametru keys
jest większa niż długość elementu items
.
-lub-
index
i length
nie określają prawidłowego zakresu w elemecie keys
Array.
-lub-
items
nie null
ma wartości i index
length
nie określa prawidłowego zakresu w elemecie items
Array.
Co najmniej jeden element w elemecie keys
Array nie implementuje interfejsu IComparable<T> ogólnego.
Przykłady
Poniższy przykład kodu przedstawia Sort<TKey,TValue>(TKey[], TValue[])przeciążenia metody , , Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ogólnej dla sortowania par tablic reprezentujących klucze i wartości.
Przykład kodu definiuje alternatywny moduł porównawczy dla ciągów o nazwie ReverseCompare
, który implementuje IComparer<string>
interfejs ogólny (IComparer(Of String)
w języku Visual Basic IComparer<String^>
w języku Visual C++). Funkcja porównywania wywołuje metodę CompareTo(String) , cofa kolejność comparands, tak aby ciągi sortowane w wysokiej do niskiej wartości zamiast niskich do wysokich.
Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów (kluczy) oraz tablicę liczb całkowitych reprezentujących maksymalną długość każdego dinozaura w metrach (wartości). Tablice są następnie sortowane i wyświetlane kilka razy:
Przeciążenie Sort<TKey,TValue>(TKey[], TValue[]) służy do sortowania obu tablic w kolejności nazw dinozaurów w pierwszej tablicy.
Przeciążenie Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) i wystąpienie
ReverseCompare
klasy są używane do odwrócenia kolejności sortowania sparowanych tablic.Przeciążenie Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) służy do sortowania ostatnich trzech elementów obu tablic.
Przeciążenie służy do sortowania Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ostatnich trzech elementów obu tablic w odwrotnej kolejności.
Uwaga
Wywołania metod ogólnych nie wyglądają inaczej niż wywołania ich niegenerycznych odpowiedników, ponieważ język Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu dwóch pierwszych argumentów. Jeśli używasz Ildasm.exe (IL Dezasembler), aby zbadać język pośredni microsoft (MSIL), możesz zobaczyć, że metody ogólne są wywoływane.
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.
Uwagi
Każdy klucz w elemencie keys
Array ma odpowiedni element w elemencie items
Array. Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie items
Array jest podobnie zmieniany. W związku z tym element items
jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w elemecie keys
Array.Array
Każdy klucz w określonym zakresie elementów w elemecie keys
Array musi zaimplementować IComparable<T> interfejs ogólny, aby móc porównać każdy inny klucz.
Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie elementu ArgumentException.
Jeśli sortowanie nie zostało ukończone pomyślnie, wyniki są niezdefiniowane.
Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:
Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .
Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .
W przeciwnym razie używa algorytmu Quicksort .
Ta implementacja wykonuje niestabilne sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilne sortowanie zachowuje kolejność elementów, które są równe.
Ta metoda jest operacją O(n
log n
), gdzie n
to length
.
Zobacz też
Dotyczy
Opinia
https://aka.ms/ContentUserFeedback.
Dostępne już wkrótce: W 2024 r. będziemy stopniowo wycofywać zgłoszenia z serwisu GitHub jako mechanizm przesyłania opinii na temat zawartości i zastępować go nowym systemem opinii. Aby uzyskać więcej informacji, sprawdź:Prześlij i wyświetl opinię dla