Array.Sort Methode
Definition
Wichtig
Einige Informationen beziehen sich auf Vorabversionen, die vor dem Release ggf. grundlegend überarbeitet werden. Microsoft übernimmt hinsichtlich der hier bereitgestellten Informationen keine Gewährleistungen, seien sie ausdrücklich oder konkludent.
Sortiert die Elemente in einem eindimensionalen Array.
Überlädt
| Name | Beschreibung |
|---|---|
| Sort(Array, Array, Int32, Int32, IComparer) |
Sortiert einen Bereich von Elementen in einem Paar eindimensionaler Array Objekte (eins enthält die Schlüssel und das andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Verwendung des angegebenen IComparer. |
| Sort(Array, Int32, Int32, IComparer) |
Sortiert die Elemente in einem Bereich von Elementen in einem eindimensionalen Array Element mithilfe der angegebenen IComparer. |
| Sort(Array, Array, Int32, Int32) |
Sortiert einen Bereich von Elementen in einem Paar eindimensionaler Array Objekte (eins enthält die Schlüssel und das andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Verwendung der IComparable Implementierung jedes Schlüssels. |
| Sort(Array, Int32, Int32) |
Sortiert die Elemente in einem Bereich von Elementen in einem eindimensionalen Array Element mithilfe der IComparable Implementierung der einzelnen Elemente der Array. |
| Sort(Array, Array, IComparer) |
Sortiert ein Paar eindimensionaler Array Objekte (eins enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Verwendung der angegebenen IComparer. |
| Sort(Array, Array) |
Sortiert ein Paar eindimensionaler Array Objekte (eins enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Verwendung der IComparable Implementierung jedes Schlüssels. |
| Sort(Array) |
Sortiert die Elemente in einem ganzen eindimensionalen Array Element mithilfe der IComparable Implementierung jedes Elements der Array. |
| Sort(Array, IComparer) |
Sortiert die Elemente in einem eindimensionalen Array Element mithilfe des angegebenen IComparer. |
| Sort<T>(T[]) |
Sortiert die Elemente in einem ganzen Array Element mithilfe der IComparable<T> generischen Schnittstellenimplementierung jedes Elements der Array. |
| Sort<T>(T[], IComparer<T>) |
Sortiert die Elemente in einer Array angegebenen IComparer<T> generischen Schnittstelle. |
| Sort<T>(T[], Comparison<T>) |
Sortiert die Elemente in einer Array mit dem angegebenen Comparison<T>. |
| Sort<T>(T[], Int32, Int32) |
Sortiert die Elemente in einem Bereich von Elementen in einer Array Verwendung der IComparable<T> generischen Schnittstellenimplementierung jedes Elements der .Array |
| Sort<T>(T[], Int32, Int32, IComparer<T>) |
Sortiert die Elemente in einem Bereich von Elementen in einer Array angegebenen IComparer<T> generischen Schnittstelle. |
| Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) |
Sortiert einen Bereich von Elementen in einem Objektpaar Array (eines enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array mithilfe der angegebenen IComparer<T> generischen Schnittstelle. |
| Sort<TKey,TValue>(TKey[], TValue[]) |
Sortiert ein Objektpaar Array (eins enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Verwendung der IComparable<T> generischen Schnittstellenimplementierung jedes Schlüssels. |
| Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) |
Sortiert ein Objektpaar Array (eins enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Mithilfe der angegebenen IComparer<T> generischen Schnittstelle. |
| Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) |
Sortiert einen Bereich von Elementen in einem Objektpaar Array (eines enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Mithilfe der IComparable<T> generischen Schnittstellenimplementierung jedes Schlüssels. |
Sort(Array, Array, Int32, Int32, IComparer)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- 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)
Parameter
- items
- Array
Das eindimensionale Array Element, das die Elemente enthält, die den einzelnen Schlüsseln in der keysArrayDatei entsprechen.
-oder-
null um nur die keysArray.
- index
- Int32
Der Anfangsindex des zu sortierenden Bereichs.
- length
- Int32
Die Anzahl der zu sortierenden Elemente im Bereich.
- comparer
- IComparer
Die IComparer Implementierung, die beim Vergleichen von Elementen verwendet werden soll.
-oder-
null die Implementierung der einzelnen Elemente zu verwenden IComparable .
Ausnahmen
keys ist null.
index ist kleiner als die untere Grenze von keys.
-oder-
length ist kleiner als 0 (null).
items ist nicht null, und die untere Grenze von keys nicht mit der unteren Grenze von items.
-oder-
items ist nicht null, und die Länge von keys ist größer als die Länge von items.
-oder-
index und length geben Sie keinen gültigen Bereich in der keysArray.
-oder-
items ist nicht null, und indexlength geben Sie keinen gültigen Bereich in der itemsArray.
-oder-
Die Implementierung, die während der comparer Sortierung einen Fehler verursacht hat. Wenn Sie beispielsweise ein Element mit sich selbst vergleichen, comparer kann "0" nicht zurückgegeben werden.
comparer ist null, und eines oder mehrere Elemente in der keysArray Schnittstelle nicht implementieren IComparable .
Beispiele
Das folgende Codebeispiel zeigt, wie zwei zugeordnete Arrays sortiert werden, wobei das erste Array die Schlüssel enthält und das zweite Array die Werte enthält. Sortierungen erfolgen mithilfe des Standardabgleichs und eines benutzerdefinierten Vergleichs, der die Sortierreihenfolge umkehrt. Beachten Sie, dass das Ergebnis je nach aktuellem CultureInfoErgebnis variieren kann.
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
Hinweise
Jeder Schlüssel in der Datei keysArray weist ein entsprechendes Element in der itemsArrayDatei auf. Wenn ein Schlüssel während der Sortierung neu positioniert wird, wird das entsprechende Element in der itemsArray Position entsprechend neu positioniert. Daher wird die itemsSortierung nach der Anordnung der entsprechenden Schlüssel in der keysArray.Array
Ist comparer dies nullder Fall, muss jeder Schlüssel innerhalb des angegebenen Elementbereichs in der keysArray Schnittstelle implementiert IComparable werden, um Vergleiche mit jedem anderen Schlüssel zu ermöglichen.
Sie können sortieren, wenn mehr Elemente als Schlüssel vorhanden sind, aber die Elemente ohne entsprechende Schlüssel werden nicht sortiert. Sie können nicht sortieren, wenn mehr Schlüssel als Elemente vorhanden sind. Dadurch wird ein ArgumentException.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
.NET enthält vordefinierte IComparer Implementierungen, die in der folgenden Tabelle aufgeführt sind.
| Implementierung | Beschreibung |
|---|---|
| System.Collections.CaseInsensitiveComparer | Vergleicht zwei Objekte, führt jedoch einen Vergleich zwischen Zeichenfolgen durch, bei dem die Groß-/Kleinschreibung nicht beachtet wird. |
| Comparer.Default | Vergleicht zwei beliebige Objekte mithilfe der Sortierkonventionen der aktuellen Kultur. |
| Comparer.DefaultInvariant | Vergleicht zwei beliebige Objekte mithilfe der Sortierkonventionen der invarianten Kultur. |
| Comparer<T>.Default | Vergleicht zwei Objekte des Typs T mithilfe der Standardsortierreihenfolge des Typs. |
Sie können auch benutzerdefinierte Vergleiche unterstützen, indem Sie eine Instanz Ihrer eigenen IComparer Implementierung für den comparer Parameter bereitstellen. In diesem Beispiel wird eine benutzerdefinierte IComparer Implementierung definiert, die die Standardsortierreihenfolge umkehrt und einen Vergleich zwischen Zeichenfolgen ohne Groß-/Kleinschreibung durchführt.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(n Protokoll n)-Vorgang, wobei n dies der Fall ist length.
Hinweise für Aufrufer
.NET Framework 4 und frühere Versionen verwendeten nur den Quicksort-Algorithmus. Quicksort identifiziert ungültige Vergleiche in einigen Situationen, in denen der Sortiervorgang eine IndexOutOfRangeException Ausnahme auslöst, und löst eine ArgumentException Ausnahme für den Aufrufer aus. Ab .NET Framework 4.5 können Sortiervorgänge, die zuvor ArgumentException ausgelöst haben, keine Ausnahme auslösen, da die Einfüge- und Heapsortalgorithmen keinen ungültigen Vergleich erkennen. Dies gilt größtenteils für Arrays mit weniger als oder gleich 16 Elementen.
Weitere Informationen
- IComparer
- IComparable
- BinarySearch
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort(Array, Int32, Int32, IComparer)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- 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)
Parameter
- index
- Int32
Der Anfangsindex des zu sortierenden Bereichs.
- length
- Int32
Die Anzahl der zu sortierenden Elemente im Bereich.
- comparer
- IComparer
Die IComparer Implementierung, die beim Vergleichen von Elementen verwendet werden soll.
-oder-
null die Implementierung der einzelnen Elemente zu verwenden IComparable .
Ausnahmen
array ist null.
array ist multidimensional.
index ist kleiner als die untere Grenze von array.
-oder-
length ist kleiner als 0 (null).
index und length geben Sie keinen gültigen Bereich in array.
-oder-
Die Implementierung, die während der comparer Sortierung einen Fehler verursacht hat. Wenn Sie beispielsweise ein Element mit sich selbst vergleichen, comparer kann "0" nicht zurückgegeben werden.
comparer ist null, und mindestens ein Element in array der IComparable Schnittstelle wird nicht implementiert.
Beispiele
Das folgende Codebeispiel zeigt, wie die Werte in einem Array Standardabgleich und einem benutzerdefinierten Vergleichselement sortiert werden, mit dem die Sortierreihenfolge umgekehrt wird. Beachten Sie, dass das Ergebnis je nach aktuellem CultureInfoErgebnis variieren kann.
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
Hinweise
Ist comparer dies der Fall null, muss jedes Element innerhalb des angegebenen Elementbereichs array die IComparable Schnittstelle implementieren, um Vergleiche mit jedem anderen Element zu arrayermöglichen.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
.NET enthält vordefinierte IComparer Implementierungen, die in der folgenden Tabelle aufgeführt sind.
| Implementierung | Beschreibung |
|---|---|
| System.Collections.CaseInsensitiveComparer | Vergleicht zwei Objekte, führt jedoch einen Vergleich zwischen Zeichenfolgen durch, bei dem die Groß-/Kleinschreibung nicht beachtet wird. |
| Comparer.Default | Vergleicht zwei beliebige Objekte mithilfe der Sortierkonventionen der aktuellen Kultur. |
| Comparer.DefaultInvariant | Vergleicht zwei beliebige Objekte mithilfe der Sortierkonventionen der invarianten Kultur. |
| Comparer<T>.Default | Vergleicht zwei Objekte des Typs T mithilfe der Standardsortierreihenfolge des Typs. |
Sie können auch benutzerdefinierte Vergleiche unterstützen, indem Sie eine Instanz Ihrer eigenen IComparer Implementierung für den comparer Parameter bereitstellen. In diesem Beispiel wird eine ReverseComparer Klasse definiert, die die Standardsortierreihenfolge für Instanzen eines Typs umkehrt und einen Vergleich der Zeichenfolgen ohne Groß-/Kleinschreibung durchführt.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(n Protokoll n)-Vorgang, wobei n dies der Fall ist length.
Hinweise für Aufrufer
.NET Framework 4 und frühere Versionen verwendeten nur den Quicksort-Algorithmus. Quicksort identifiziert ungültige Vergleiche in einigen Situationen, in denen der Sortiervorgang eine IndexOutOfRangeException Ausnahme auslöst, und löst eine ArgumentException Ausnahme für den Aufrufer aus. Ab .NET Framework 4.5 können Sortiervorgänge, die zuvor ArgumentException ausgelöst haben, keine Ausnahme auslösen, da die Einfüge- und Heapsortalgorithmen keinen ungültigen Vergleich erkennen. Dies gilt größtenteils für Arrays mit weniger als oder gleich 16 Elementen.
Weitere Informationen
- IComparer
- IComparable
- BinarySearch
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort(Array, Array, Int32, Int32)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert einen Bereich von Elementen in einem Paar eindimensionaler Array Objekte (eins enthält die Schlüssel und das andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Verwendung der IComparable Implementierung jedes Schlüssels.
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)
Parameter
- items
- Array
Das eindimensionale Array Element, das die Elemente enthält, die den einzelnen Schlüsseln in der keysArrayDatei entsprechen.
-oder-
null um nur die keysArray.
- index
- Int32
Der Anfangsindex des zu sortierenden Bereichs.
- length
- Int32
Die Anzahl der zu sortierenden Elemente im Bereich.
Ausnahmen
keys ist null.
index ist kleiner als die untere Grenze von keys.
-oder-
length ist kleiner als 0 (null).
items ist nicht null, und die Länge von keys ist größer als die Länge von items.
-oder-
index und length geben Sie keinen gültigen Bereich in der keysArray.
-oder-
items ist nicht null, und indexlength geben Sie keinen gültigen Bereich in der itemsArray.
Mindestens ein Element in der keysArray Schnittstelle wird nicht implementiert IComparable .
Beispiele
Das folgende Codebeispiel zeigt, wie zwei zugeordnete Arrays sortiert werden, wobei das erste Array die Schlüssel enthält und das zweite Array die Werte enthält. Sortierungen erfolgen mithilfe des Standardabgleichs und eines benutzerdefinierten Vergleichs, der die Sortierreihenfolge umkehrt. Beachten Sie, dass das Ergebnis je nach aktuellem CultureInfoErgebnis variieren kann.
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
Hinweise
Jeder Schlüssel in der Datei keysArray weist ein entsprechendes Element in der itemsArrayDatei auf. Wenn ein Schlüssel während der Sortierung neu positioniert wird, wird das entsprechende Element in der itemsArray Position entsprechend neu positioniert. Daher wird die itemsSortierung nach der Anordnung der entsprechenden Schlüssel in der keysArray.Array
Jeder Schlüssel innerhalb des angegebenen Elementbereichs in der keysArray Muss die IComparable Schnittstelle implementieren, um Vergleiche mit jedem anderen Schlüssel zu ermöglichen.
Sie können sortieren, wenn mehr Elemente als Schlüssel vorhanden sind, aber die Elemente ohne entsprechende Schlüssel werden nicht sortiert. Sie können nicht sortieren, wenn mehr Schlüssel als Elemente vorhanden sind. Dadurch wird ein ArgumentException.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(n Protokoll n)-Vorgang, wobei n dies der Fall ist length.
Weitere Informationen
Gilt für:
Sort(Array, Int32, Int32)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert die Elemente in einem Bereich von Elementen in einem eindimensionalen Array Element mithilfe der IComparable Implementierung der einzelnen Elemente der 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)
Parameter
- index
- Int32
Der Anfangsindex des zu sortierenden Bereichs.
- length
- Int32
Die Anzahl der zu sortierenden Elemente im Bereich.
Ausnahmen
array ist null.
array ist multidimensional.
index ist kleiner als die untere Grenze von array.
-oder-
length ist kleiner als 0 (null).
index und length geben Sie keinen gültigen Bereich in array.
Mindestens ein Element in array der IComparable Schnittstelle wird nicht implementiert.
Beispiele
Das folgende Codebeispiel zeigt, wie die Werte in einem Array Standardabgleich und einem benutzerdefinierten Vergleichselement sortiert werden, mit dem die Sortierreihenfolge umgekehrt wird. Beachten Sie, dass das Ergebnis je nach aktuellem CultureInfoErgebnis variieren kann.
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
Hinweise
Jedes Element innerhalb des angegebenen Elementbereichs in array muss die IComparable Schnittstelle implementieren, um Vergleiche mit jedem anderen Element in arrayder Lage zu sein.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(n Protokoll n)-Vorgang, wobei n dies der Fall ist length.
Weitere Informationen
Gilt für:
Sort(Array, Array, IComparer)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- 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)
Parameter
- items
- Array
Das eindimensionale Array Element, das die Elemente enthält, die den einzelnen Schlüsseln in der keysArrayDatei entsprechen.
-oder-
null um nur die keysArray.
- comparer
- IComparer
Die IComparer Implementierung, die beim Vergleichen von Elementen verwendet werden soll.
-oder-
null die Implementierung der einzelnen Elemente zu verwenden IComparable .
Ausnahmen
keys ist null.
items ist nicht null, und die Länge von keys ist größer als die Länge von items.
-oder-
Die Implementierung, die während der comparer Sortierung einen Fehler verursacht hat. Wenn Sie beispielsweise ein Element mit sich selbst vergleichen, comparer kann "0" nicht zurückgegeben werden.
comparer ist null, und eines oder mehrere Elemente in der keysArray Schnittstelle nicht implementieren IComparable .
Beispiele
Das folgende Beispiel zeigt, wie zwei zugeordnete Arrays sortiert werden, bei denen das erste Array die Schlüssel enthält und das zweite Array die Werte enthält. Sortierungen erfolgen mithilfe des Standardabgleichs und eines benutzerdefinierten Vergleichs, der die Sortierreihenfolge umkehrt. Beachten Sie, dass das Ergebnis je nach aktuellem CultureInfoErgebnis variieren kann.
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
Hinweise
Jeder Schlüssel in der Datei keysArray weist ein entsprechendes Element in der itemsArrayDatei auf. Wenn ein Schlüssel während der Sortierung neu positioniert wird, wird das entsprechende Element in der itemsArray Position entsprechend neu positioniert. Daher wird die itemsSortierung nach der Anordnung der entsprechenden Schlüssel in der keysArray.Array
Wenn comparer ja null, muss jeder Schlüssel in der keysArray Schnittstelle implementieren IComparable , um Vergleiche mit jedem anderen Schlüssel durchführen zu können.
Sie können sortieren, wenn mehr Elemente als Schlüssel vorhanden sind, aber die Elemente ohne entsprechende Schlüssel werden nicht sortiert. Sie können nicht sortieren, wenn mehr Schlüssel als Elemente vorhanden sind. Dadurch wird ein ArgumentException.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
.NET enthält vordefinierte IComparer Implementierungen, die in der folgenden Tabelle aufgeführt sind.
| Implementierung | Beschreibung |
|---|---|
| System.Collections.CaseInsensitiveComparer | Vergleicht zwei Objekte, führt jedoch einen Vergleich zwischen Zeichenfolgen durch, bei dem die Groß-/Kleinschreibung nicht beachtet wird. |
| Comparer.Default | Vergleicht zwei beliebige Objekte mithilfe der Sortierkonventionen der aktuellen Kultur. |
| Comparer.DefaultInvariant | Vergleicht zwei beliebige Objekte mithilfe der Sortierkonventionen der invarianten Kultur. |
| Comparer<T>.Default | Vergleicht zwei Objekte des Typs T mithilfe der Standardsortierreihenfolge des Typs. |
Sie können auch benutzerdefinierte Vergleiche unterstützen, indem Sie eine Instanz Ihrer eigenen IComparer Implementierung für den comparer Parameter bereitstellen. In diesem Beispiel wird eine IComparer Implementierung definiert, die die Standardsortierreihenfolge umkehrt und einen Vergleich zwischen Zeichenfolgen ohne Groß-/Kleinschreibung durchführt.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(Protokoll)-Vorgang, bei dem n es sich um einen Length Okeys(n-Protokolln)-Vorgang handelt.
Hinweise für Aufrufer
.NET Framework 4 und frühere Versionen verwendeten nur den Quicksort-Algorithmus. Quicksort identifiziert ungültige Vergleiche in einigen Situationen, in denen der Sortiervorgang eine IndexOutOfRangeException Ausnahme auslöst, und löst eine ArgumentException Ausnahme für den Aufrufer aus. Ab .NET Framework 4.5 können Sortiervorgänge, die zuvor ArgumentException ausgelöst haben, keine Ausnahme auslösen, da die Einfüge- und Heapsortalgorithmen keinen ungültigen Vergleich erkennen. Dies gilt größtenteils für Arrays mit weniger als oder gleich 16 Elementen.
Weitere Informationen
- IComparer
- IComparable
- BinarySearch
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort(Array, Array)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert ein Paar eindimensionaler Array Objekte (eins enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Verwendung der IComparable Implementierung jedes Schlüssels.
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)
Parameter
- items
- Array
Das eindimensionale Array Element, das die Elemente enthält, die den einzelnen Schlüsseln in der keysArrayDatei entsprechen.
-oder-
null um nur die keysArray.
Ausnahmen
keys ist null.
items ist nicht null, und die Länge von keys ist größer als die Länge von items.
Mindestens ein Element in der keysArray Schnittstelle wird nicht implementiert IComparable .
Beispiele
Das folgende Beispiel zeigt, wie zwei zugeordnete Arrays sortiert werden, bei denen das erste Array die Schlüssel enthält und das zweite Array die Werte enthält. Sortierungen erfolgen mithilfe des Standardabgleichs und eines benutzerdefinierten Vergleichs, der die Sortierreihenfolge umkehrt. Beachten Sie, dass das Ergebnis je nach aktuellem CultureInfoErgebnis variieren kann.
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
Hinweise
Jeder Schlüssel in der Datei keysArray weist ein entsprechendes Element in der itemsArrayDatei auf. Wenn ein Schlüssel während der Sortierung neu positioniert wird, wird das entsprechende Element in der itemsArray Position entsprechend neu positioniert. Daher wird die itemsSortierung nach der Anordnung der entsprechenden Schlüssel in der keysArray.Array
Jeder Schlüssel in der keysArray Muss die IComparable Schnittstelle implementieren, um Vergleiche mit jedem anderen Schlüssel zu erhalten.
Sie können sortieren, wenn mehr Elemente als Schlüssel vorhanden sind, aber die Elemente ohne entsprechende Schlüssel werden nicht sortiert. Sie können nicht sortieren, wenn mehr Schlüssel als Elemente vorhanden sind. Dadurch wird ein ArgumentException.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(Protokoll)-Vorgang, bei dem n es sich um einen Length Okeys(n-Protokolln)-Vorgang handelt.
Weitere Informationen
- IComparable
- BinarySearch
- IDictionary
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort(Array)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert die Elemente in einem ganzen eindimensionalen Array Element mithilfe der IComparable Implementierung jedes Elements der 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)
Parameter
Ausnahmen
array ist null.
array ist multidimensional.
Mindestens ein Element in array der IComparable Schnittstelle wird nicht implementiert.
Beispiele
Das folgende Codebeispiel zeigt, wie die Werte in einem Array Standardabgleich und einem benutzerdefinierten Vergleichselement sortiert werden, mit dem die Sortierreihenfolge umgekehrt wird. Beachten Sie, dass das Ergebnis je nach aktuellem CultureInfoErgebnis variieren kann.
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
Hinweise
Jedes Element von array muss die IComparable Schnittstelle implementieren, um Vergleiche mit jedem anderen Element in array.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(Protokoll)-Vorgang, bei dem n es sich um einen Length Oarray(n-Protokolln)-Vorgang handelt.
Weitere Informationen
Gilt für:
Sort(Array, IComparer)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- 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)
Parameter
- array
- Array
Das eindimensionale Array, das sortiert werden soll.
- comparer
- IComparer
Die Implementierung, die beim Vergleichen von Elementen verwendet werden soll.
-oder-
null die Implementierung der einzelnen Elemente zu verwenden IComparable .
Ausnahmen
array ist null.
array ist multidimensional.
comparer ist null, und mindestens ein Element in array der IComparable Schnittstelle wird nicht implementiert.
Die Implementierung, die während der comparer Sortierung einen Fehler verursacht hat. Wenn Sie beispielsweise ein Element mit sich selbst vergleichen, comparer kann "0" nicht zurückgegeben werden.
Beispiele
Im folgenden Beispiel werden die Werte in einem Zeichenfolgenarray mithilfe des Standardvergleichs sortiert. Außerdem wird eine benutzerdefinierte IComparer Implementierung definiert ReverseComparer , die die Standardsortierreihenfolge eines Objekts umkehrt, während bei einem Vergleich zwischen Zeichenfolgen ohne Groß-/Kleinschreibung unterschieden wird. Beachten Sie, dass die Ausgabe je nach aktueller Kultur variieren kann.
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
Hinweise
Wenn comparer ja null, muss jedes Element array die IComparable Schnittstelle implementieren, um Vergleiche mit jedem anderen Element in array.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(Protokoll)-Vorgang, bei dem n es sich um einen Length Oarray(n-Protokolln)-Vorgang handelt.
.NET enthält vordefinierte IComparer Implementierungen, die in der folgenden Tabelle aufgeführt sind.
| Implementierung | Beschreibung |
|---|---|
| System.Collections.CaseInsensitiveComparer | Vergleicht zwei Objekte, führt jedoch einen Vergleich zwischen Zeichenfolgen durch, bei dem die Groß-/Kleinschreibung nicht beachtet wird. |
| Comparer.Default | Vergleicht zwei beliebige Objekte mithilfe der Sortierkonventionen der aktuellen Kultur. |
| Comparer.DefaultInvariant | Vergleicht zwei beliebige Objekte mithilfe der Sortierkonventionen der invarianten Kultur. |
| Comparer<T>.Default | Vergleicht zwei Objekte des Typs T mithilfe der Standardsortierreihenfolge des Typs. |
Sie können auch benutzerdefinierte Vergleiche unterstützen, indem Sie eine Instanz Ihrer eigenen IComparer Implementierung für den comparer Parameter bereitstellen. In diesem Beispiel wird eine ReverseComparer Klasse definiert, die die Standardsortierreihenfolge für Instanzen eines Typs umkehrt und einen Vergleich der Zeichenfolgen ohne Groß-/Kleinschreibung durchführt.
Hinweise für Aufrufer
.NET Framework 4 und frühere Versionen verwendeten nur den Quicksort-Algorithmus. Quicksort identifiziert ungültige Vergleiche in einigen Situationen, in denen der Sortiervorgang eine IndexOutOfRangeException Ausnahme auslöst, und löst eine ArgumentException Ausnahme für den Aufrufer aus. Ab .NET Framework 4.5 können Sortiervorgänge, die zuvor ArgumentException ausgelöst haben, keine Ausnahme auslösen, da die Einfüge- und Heapsortalgorithmen keinen ungültigen Vergleich erkennen. Dies gilt größtenteils für Arrays mit weniger als oder gleich 16 Elementen.
Weitere Informationen
- IComparer
- IComparable
- BinarySearch
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort<T>(T[])
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert die Elemente in einem ganzen Array Element mithilfe der IComparable<T> generischen Schnittstellenimplementierung jedes Elements der 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())
Typparameter
- T
Der Typ der Elemente des Arrays.
Parameter
- array
- T[]
Die eindimensionale, nullbasierte Array Sortierung.
Ausnahmen
array ist null.
Mindestens ein Element in array der IComparable<T> Generischen Schnittstelle wird nicht implementiert.
Beispiele
Im folgenden Codebeispiel wird die Sort<T>(T[]) generische Methodenüberladung und die BinarySearch<T>(T[], T) generische Methodenüberladung veranschaulicht. Ein Array von Zeichenfolgen wird in keiner bestimmten Reihenfolge erstellt.
Das Array wird angezeigt, sortiert und erneut angezeigt.
Anmerkung
Die Aufrufe der Sort und BinarySearch generischen Methoden unterscheiden sich nicht von Aufrufen ihrer nichtgenerischen Entsprechungen, da Visual Basic, C# und C++ den Typ des generischen Typparameters vom Typ des ersten Arguments ableiten. Wenn Sie die Ildasm.exe (IL Disassembler) verwenden, um die Microsoft Zwischensprache (MSIL) zu untersuchen, können Sie sehen, dass die generischen Methoden aufgerufen werden.
Die BinarySearch<T>(T[], T) generische Methodenüberladung wird dann verwendet, um nach zwei Zeichenfolgen zu suchen, eines, das sich nicht im Array befindet und eines, das heißt. Das Array und der Rückgabewert der BinarySearch Methode werden an die ShowWhere generische Methode übergeben, die den Indexwert anzeigt, wenn die Zeichenfolge gefunden wird, und andernfalls fallen die Elemente, zwischen denen die Suchzeichenfolge liegt, wenn sie sich im Array befand. The index is negative if the string is not n the array, so the ShowWhere method takes the bitwise complement (the ~ operator in C#, Xor -1 in Visual Basic), to obtain the index of the first element in the list that is larger than the search string.
using 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.
Hinweise
Jedes Element von array muss die IComparable<T> generische Schnittstelle implementieren, um Vergleiche mit jedem anderen Element in array.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(Protokoll)-Vorgang, bei dem n es sich um einen Length Oarray(n-Protokolln)-Vorgang handelt.
Weitere Informationen
Gilt für:
Sort<T>(T[], IComparer<T>)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert die Elemente in einer Array angegebenen IComparer<T> generischen Schnittstelle.
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))
Typparameter
- T
Der Typ der Elemente des Arrays.
Parameter
- array
- T[]
Die eindimensionale Nullbasis Array , die sortiert werden soll.
- comparer
- IComparer<T>
Die IComparer<T> generische Schnittstellenimplementierung, die beim Vergleichen von Elementen verwendet werden soll, oder null um die IComparable<T> generische Schnittstellenimplementierung der einzelnen Elemente zu verwenden.
Ausnahmen
array ist null.
comparer ist null, und mindestens ein Element, in array dem die IComparable<T> generische Schnittstelle nicht implementiert wird.
Die Implementierung, die während der comparer Sortierung einen Fehler verursacht hat. Wenn Sie beispielsweise ein Element mit sich selbst vergleichen, comparer kann "0" nicht zurückgegeben werden.
Beispiele
Im folgenden Codebeispiel wird die Sort<T>(T[], IComparer<T>) generische Methodenüberladung und die BinarySearch<T>(T[], T, IComparer<T>) generische Methodenüberladung veranschaulicht.
Im Codebeispiel wird ein alternativer Comparer für Zeichenfolgen mit dem Namen ReverseCompare definiert, der die generische Schnittstelle IComparer<string> (IComparer(Of String) in Visual Basic,) implementiert. Der Comparer ruft die CompareTo(String) Methode auf, wobei die Reihenfolge der Vergleiche umgekehrt wird, sodass die Zeichenfolgen anstelle von "niedrig" nach "hoch" sortieren.
Das Array wird angezeigt, sortiert und erneut angezeigt. Arrays müssen sortiert werden, um die BinarySearch Methode zu verwenden.
Anmerkung
Die Aufrufe der Sort<T>(T[], IComparer<T>) und BinarySearch<T>(T[], T, IComparer<T>) generischen Methoden unterscheiden sich nicht von Aufrufen ihrer nichtgenerischen Entsprechungen, da Visual Basic, C# und C++ den Typ des generischen Typparameters vom Typ des ersten Arguments ableiten. Wenn Sie die Ildasm.exe (IL Disassembler) verwenden, um die Microsoft Zwischensprache (MSIL) zu untersuchen, können Sie sehen, dass die generischen Methoden aufgerufen werden.
Die BinarySearch<T>(T[], T, IComparer<T>) generische Methodenüberladung wird dann verwendet, um nach zwei Zeichenfolgen zu suchen, eines, das sich nicht im Array befindet und eines, das heißt. Das Array und der Rückgabewert der BinarySearch<T>(T[], T, IComparer<T>) Methode werden an die ShowWhere generische Methode übergeben, die den Indexwert anzeigt, wenn die Zeichenfolge gefunden wird, und andernfalls fallen die Elemente, zwischen denen die Suchzeichenfolge liegt, wenn sie sich im Array befand. The index is negative if the string is not n the array, so the ShowWhere method takes the bitwise complement (the ~ operator in C#, Xor -1 in Visual Basic), to obtain the index of the first element in the list that is larger than the search string.
using 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.
Hinweise
Wenn comparer ja null, muss jedes Element array die IComparable<T> generische Schnittstelle implementieren, um Vergleiche mit jedem anderen Element in array.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(Protokoll)-Vorgang, bei dem n es sich um einen Length Oarray(n-Protokolln)-Vorgang handelt.
Hinweise für Aufrufer
.NET Framework 4 und frühere Versionen verwendeten nur den Quicksort-Algorithmus. Quicksort identifiziert ungültige Vergleiche in einigen Situationen, in denen der Sortiervorgang eine IndexOutOfRangeException Ausnahme auslöst, und löst eine ArgumentException Ausnahme für den Aufrufer aus. Ab .NET Framework 4.5 können Sortiervorgänge, die zuvor ArgumentException ausgelöst haben, keine Ausnahme auslösen, da die Einfüge- und Heapsortalgorithmen keinen ungültigen Vergleich erkennen. Dies gilt größtenteils für Arrays mit weniger als oder gleich 16 Elementen.
Weitere Informationen
- IComparer<T>
- IComparable<T>
- BinarySearch
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort<T>(T[], Comparison<T>)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert die Elemente in einer Array mit dem angegebenen Comparison<T>.
public:
generic <typename T>
static void Sort(cli::array <T> ^ array, Comparison<T> ^ comparison);
public static void Sort<T>(T[] array, Comparison<T> comparison);
static member Sort : 'T[] * Comparison<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), comparison As Comparison(Of T))
Typparameter
- T
Der Typ der Elemente des Arrays.
Parameter
- array
- T[]
Die eindimensionale, nullbasierte Array Sortierung.
- comparison
- Comparison<T>
Die Comparison<T> beim Vergleichen von Elementen zu verwendende Verwendung.
Ausnahmen
Die Implementierung, die während der comparison Sortierung einen Fehler verursacht hat. Wenn Sie beispielsweise ein Element mit sich selbst vergleichen, comparison kann "0" nicht zurückgegeben werden.
Beispiele
Im folgenden Codebeispiel wird die Sort(Comparison<T>) Methodenüberladung veranschaulicht.
Das Codebeispiel definiert eine alternative Vergleichsmethode für Zeichenfolgen mit dem Namen CompareDinosByLength. Diese Methode funktioniert wie folgt: Zuerst werden die Comparands getestetnull, und ein Nullverweis wird als kleiner als ein Nullwert behandelt. Zweitens werden die Zeichenfolgenlängen verglichen, und die längere Zeichenfolge gilt als größer. Drittens wird der normale Zeichenfolgenvergleich verwendet, wenn die Längen gleich sind.
Ein Array von Zeichenfolgen wird erstellt und mit vier Zeichenfolgen in keiner bestimmten Reihenfolge aufgefüllt. Die Liste enthält auch eine leere Zeichenfolge und einen Nullverweis. Die Liste wird angezeigt, sortiert mit einem Comparison<T> generischen Delegaten, der die CompareDinosByLength Methode darstellt, und erneut angezeigt.
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"
Hinweise
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den Algorithmus für die introspektive Sortierung (Introsortierung) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(Protokoll)-Vorgang, bei dem n es sich um einen Length Oarray(n-Protokolln)-Vorgang handelt.
Hinweise für Aufrufer
.NET Framework 4 und frühere Versionen verwendeten nur den Quicksort-Algorithmus. Quicksort identifiziert ungültige Vergleiche in einigen Situationen, in denen der Sortiervorgang eine IndexOutOfRangeException Ausnahme auslöst, und löst eine ArgumentException Ausnahme für den Aufrufer aus. Ab .NET Framework 4.5 können Sortiervorgänge, die zuvor ArgumentException ausgelöst haben, keine Ausnahme auslösen, da die Einfüge- und Heapsortalgorithmen keinen ungültigen Vergleich erkennen. Dies gilt größtenteils für Arrays mit weniger als oder gleich 6 Elementen.
Weitere Informationen
Gilt für:
Sort<T>(T[], Int32, Int32)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert die Elemente in einem Bereich von Elementen in einer Array Verwendung der IComparable<T> generischen Schnittstellenimplementierung jedes Elements der .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)
Typparameter
- T
Der Typ der Elemente des Arrays.
Parameter
- array
- T[]
Die eindimensionale, nullbasierte Array Sortierung.
- index
- Int32
Der Anfangsindex des zu sortierenden Bereichs.
- length
- Int32
Die Anzahl der zu sortierenden Elemente im Bereich.
Ausnahmen
array ist null.
index ist kleiner als die untere Grenze von array.
-oder-
length ist kleiner als 0 (null).
index und length geben Sie keinen gültigen Bereich in array.
Mindestens ein Element in array der IComparable<T> Generischen Schnittstelle wird nicht implementiert.
Beispiele
Im folgenden Codebeispiel wird die Sort<T>(T[], Int32, Int32) generische Methodenüberladung und die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generische Methodenüberladung zum Sortieren eines Bereichs in einem Array veranschaulicht.
Im Codebeispiel wird ein alternativer Comparer für Zeichenfolgen mit dem Namen ReverseCompare definiert, der die generische Schnittstelle IComparer<string> (IComparer(Of String) in Visual Basic) implementiert. Der Comparer ruft die CompareTo(String) Methode auf, wobei die Reihenfolge der Vergleiche umgekehrt wird, sodass die Zeichenfolgen anstelle von "niedrig" nach "hoch" sortieren.
Das Codebeispiel erstellt und zeigt ein Array von Dinosauriernamen an, bestehend aus drei Herbivoren gefolgt von drei Karnivoren (Tyrannosauriden, um genau zu sein). Die Sort<T>(T[], Int32, Int32) generische Methodenüberladung wird verwendet, um die letzten drei Elemente des Arrays zu sortieren, die dann angezeigt wird. Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generische Methodenüberladung wird verwendet ReverseCompare , um die letzten drei Elemente in umgekehrter Reihenfolge zu sortieren. Die gründlich verwechselten Dinosaurier werden wieder angezeigt.
Anmerkung
Die Aufrufe der Sort<T>(T[], IComparer<T>) und BinarySearch<T>(T[], T, IComparer<T>) generischen Methoden unterscheiden sich nicht von Aufrufen ihrer nichtgenerischen Entsprechungen, da Visual Basic, C# und C++ den Typ des generischen Typparameters vom Typ des ersten Arguments ableiten. Wenn Sie die Ildasm.exe (IL Disassembler) verwenden, um die Microsoft Zwischensprache (MSIL) zu untersuchen, können Sie sehen, dass die generischen Methoden aufgerufen werden.
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
Hinweise
Jedes Element innerhalb des angegebenen Elementbereichs in array muss die IComparable<T> generische Schnittstelle implementieren, um Vergleiche mit jedem anderen Element zu arrayermöglichen.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(n Protokoll n)-Vorgang, wobei n dies der Fall ist length.
Weitere Informationen
Gilt für:
Sort<T>(T[], Int32, Int32, IComparer<T>)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert die Elemente in einem Bereich von Elementen in einer Array angegebenen IComparer<T> generischen Schnittstelle.
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))
Typparameter
- T
Der Typ der Elemente des Arrays.
Parameter
- array
- T[]
Die eindimensionale, nullbasierte Array Sortierung.
- index
- Int32
Der Anfangsindex des zu sortierenden Bereichs.
- length
- Int32
Die Anzahl der zu sortierenden Elemente im Bereich.
- comparer
- IComparer<T>
Die IComparer<T> generische Schnittstellenimplementierung, die beim Vergleichen von Elementen verwendet werden soll, oder null um die IComparable<T> generische Schnittstellenimplementierung der einzelnen Elemente zu verwenden.
Ausnahmen
array ist null.
index ist kleiner als die untere Grenze von array.
-oder-
length ist kleiner als 0 (null).
index und length geben Sie keinen gültigen Bereich in array.
-oder-
Die Implementierung, die während der comparer Sortierung einen Fehler verursacht hat. Wenn Sie beispielsweise ein Element mit sich selbst vergleichen, comparer kann "0" nicht zurückgegeben werden.
comparer ist null, und mindestens ein Element, in array dem die IComparable<T> generische Schnittstelle nicht implementiert wird.
Beispiele
Im folgenden Codebeispiel wird die Sort<T>(T[], Int32, Int32) generische Methodenüberladung und die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generische Methodenüberladung zum Sortieren eines Bereichs in einem Array veranschaulicht.
Im Codebeispiel wird ein alternativer Comparer für Zeichenfolgen mit dem Namen ReverseCompare definiert, der die generische Schnittstelle IComparer<string> (IComparer(Of String) in Visual Basic) implementiert. Der Comparer ruft die CompareTo(String) Methode auf, wobei die Reihenfolge der Vergleiche umgekehrt wird, sodass die Zeichenfolgen anstelle von "niedrig" nach "hoch" sortieren.
Das Codebeispiel erstellt und zeigt ein Array von Dinosauriernamen an, bestehend aus drei Herbivoren gefolgt von drei Karnivoren (Tyrannosauriden, um genau zu sein). Die Sort<T>(T[], Int32, Int32) generische Methodenüberladung wird verwendet, um die letzten drei Elemente des Arrays zu sortieren, die dann angezeigt wird. Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generische Methodenüberladung wird verwendet ReverseCompare , um die letzten drei Elemente in umgekehrter Reihenfolge zu sortieren. Die gründlich verwechselten Dinosaurier werden wieder angezeigt.
Anmerkung
Die Aufrufe der Sort<T>(T[], IComparer<T>) und BinarySearch<T>(T[], T, IComparer<T>) generischen Methoden unterscheiden sich nicht von Aufrufen ihrer nichtgenerischen Entsprechungen, da Visual Basic, C# und C++ den Typ des generischen Typparameters vom Typ des ersten Arguments ableiten. Wenn Sie die Ildasm.exe (IL Disassembler) verwenden, um die Microsoft Zwischensprache (MSIL) zu untersuchen, können Sie sehen, dass die generischen Methoden aufgerufen werden.
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
Hinweise
Wenn comparer dies der Fall ist null, muss jedes Element innerhalb des angegebenen Elementbereichs array die IComparable<T> generische Schnittstelle implementieren, um Vergleiche mit jedem anderen Element in array.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(n Protokoll n)-Vorgang, wobei n dies der Fall ist length.
Hinweise für Aufrufer
.NET Framework 4 und frühere Versionen verwendeten nur den Quicksort-Algorithmus. Quicksort identifiziert ungültige Vergleiche in einigen Situationen, in denen der Sortiervorgang eine IndexOutOfRangeException Ausnahme auslöst, und löst eine ArgumentException Ausnahme für den Aufrufer aus. Ab .NET Framework 4.5 können Sortiervorgänge, die zuvor ArgumentException ausgelöst haben, keine Ausnahme auslösen, da die Einfüge- und Heapsortalgorithmen keinen ungültigen Vergleich erkennen. Dies gilt größtenteils für Arrays mit weniger als oder gleich 16 Elementen.
Weitere Informationen
- IComparer<T>
- IComparable<T>
- BinarySearch
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert einen Bereich von Elementen in einem Objektpaar Array (eines enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array mithilfe der angegebenen IComparer<T> generischen Schnittstelle.
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))
Typparameter
- TKey
Der Typ der Elemente des Schlüsselarrays.
- TValue
Der Typ der Elemente des Elementarrays.
Parameter
- keys
- TKey[]
Die eindimensionale nullbasierte Array , die die zu sortierenden Schlüssel enthält.
- items
- TValue[]
Das eindimensionale, nullbasierte Array Element, das die Elemente enthält, die den Schlüsseln keysentsprechen, oder null nur zu sortieren keys.
- index
- Int32
Der Anfangsindex des zu sortierenden Bereichs.
- length
- Int32
Die Anzahl der zu sortierenden Elemente im Bereich.
- comparer
- IComparer<TKey>
Die IComparer<T> generische Schnittstellenimplementierung, die beim Vergleichen von Elementen verwendet werden soll, oder null um die IComparable<T> generische Schnittstellenimplementierung der einzelnen Elemente zu verwenden.
Ausnahmen
keys ist null.
index ist kleiner als die untere Grenze von keys.
-oder-
length ist kleiner als 0 (null).
items ist nicht null, und die untere Grenze von keys nicht mit der unteren Grenze von items.
-oder-
items ist nicht null, und die Länge von keys ist größer als die Länge von items.
-oder-
index und length geben Sie keinen gültigen Bereich in der keysArray.
-oder-
items ist nicht null, und indexlength geben Sie keinen gültigen Bereich in der itemsArray.
-oder-
Die Implementierung, die während der comparer Sortierung einen Fehler verursacht hat. Wenn Sie beispielsweise ein Element mit sich selbst vergleichen, comparer kann "0" nicht zurückgegeben werden.
comparer ist null, und eines oder mehrere Elemente in der keysArray generischen Schnittstelle nicht implementieren IComparable<T> .
Beispiele
Im folgenden Codebeispiel werden die Überladungen , Sort<TKey,TValue>(TKey[], TValue[])Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)und Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generische Methoden für das Sortieren von Arrays veranschaulicht, die Schlüssel und Werte darstellen.
Im Codebeispiel wird ein alternativer Comparer für Zeichenfolgen mit dem Namen ReverseCompare definiert, der die generische Schnittstelle IComparer<string>(IComparer(Of String) in Visual Basic) implementiert. Der Comparer ruft die CompareTo(String) Methode auf, wobei die Reihenfolge der Vergleiche umgekehrt wird, sodass die Zeichenfolgen anstelle von "niedrig" nach "hoch" sortieren.
Das Codebeispiel erstellt und zeigt ein Array von Dinosauriernamen (die Schlüssel) und ein Array von ganzen Zahlen an, die die maximale Länge jedes Dinosauriers in Metern (die Werte) darstellen. Die Arrays werden dann mehrmals sortiert und angezeigt:
- Die Sort<TKey,TValue>(TKey[], TValue[]) Überladung wird verwendet, um beide Arrays in der Reihenfolge der Dinosauriernamen im ersten Array zu sortieren.
- Die Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) Überladung und eine Instanz von
ReverseComparewerden verwendet, um die Sortierreihenfolge der gekoppelten Arrays umzukehren. - Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) Überladung wird verwendet, um die letzten drei Elemente beider Arrays zu sortieren.
- Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Überladung wird verwendet, um die letzten drei Elemente beider Arrays in umgekehrter Reihenfolge zu sortieren.
Anmerkung
Die Aufrufe der generischen Methoden unterscheiden sich nicht von Aufrufen ihrer nichtgenerischen Entsprechungen, da Visual Basic, C# und C++ den Typ des generischen Typparameters vom Typ der ersten beiden Argumente ableiten. Wenn Sie die Ildasm.exe (IL Disassembler) verwenden, um die Microsoft Zwischensprache (MSIL) zu untersuchen, können Sie sehen, dass die generischen Methoden aufgerufen werden.
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.
Hinweise
Jeder Schlüssel in der Datei keysArray weist ein entsprechendes Element in der itemsArrayDatei auf. Wenn ein Schlüssel während der Sortierung neu positioniert wird, wird das entsprechende Element in der itemsArray Position entsprechend neu positioniert. Daher wird die itemsSortierung nach der Anordnung der entsprechenden Schlüssel in der keysArray.Array
Ist comparer dies nullder Fall, muss jeder Schlüssel innerhalb des angegebenen Elementbereichs in der keysArray generischen Schnittstelle implementiert IComparable<T> werden, um Vergleiche mit jedem anderen Schlüssel zu ermöglichen.
Sie können sortieren, wenn mehr Elemente als Schlüssel vorhanden sind, aber die Elemente ohne entsprechende Schlüssel werden nicht sortiert. Sie können nicht sortieren, wenn mehr Schlüssel als Elemente vorhanden sind. Dadurch wird ein ArgumentException.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(n Protokoll n)-Vorgang, wobei n dies der Fall ist length.
Hinweise für Aufrufer
.NET Framework 4 und frühere Versionen verwendeten nur den Quicksort-Algorithmus. Quicksort identifiziert ungültige Vergleiche in einigen Situationen, in denen der Sortiervorgang eine IndexOutOfRangeException Ausnahme auslöst, und löst eine ArgumentException Ausnahme für den Aufrufer aus. Ab .NET Framework 4.5 können Sortiervorgänge, die zuvor ArgumentException ausgelöst haben, keine Ausnahme auslösen, da die Einfüge- und Heapsortalgorithmen keinen ungültigen Vergleich erkennen. Dies gilt größtenteils für Arrays mit weniger als oder gleich 16 Elementen.
Weitere Informationen
- IComparer<T>
- IComparable<T>
- BinarySearch
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort<TKey,TValue>(TKey[], TValue[])
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert ein Objektpaar Array (eins enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Verwendung der IComparable<T> generischen Schnittstellenimplementierung jedes Schlüssels.
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())
Typparameter
- TKey
Der Typ der Elemente des Schlüsselarrays.
- TValue
Der Typ der Elemente des Elementarrays.
Parameter
- keys
- TKey[]
Die eindimensionale nullbasierte Array , die die zu sortierenden Schlüssel enthält.
- items
- TValue[]
Das eindimensionale, nullbasierte Array Element, das die Elemente enthält, die den Schlüsseln keysentsprechen, oder null nur zu sortieren keys.
Ausnahmen
keys ist null.
items ist nicht null, und die untere Grenze von keys nicht mit der unteren Grenze von items.
-oder-
items ist nicht null, und die Länge von keys ist größer als die Länge von items.
Mindestens ein Element in der keysArray generischen Schnittstelle wird nicht implementiert IComparable<T> .
Beispiele
Im folgenden Codebeispiel werden die Überladungen , Sort<TKey,TValue>(TKey[], TValue[])Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)und Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generische Methoden für das Sortieren von Arrays veranschaulicht, die Schlüssel und Werte darstellen.
Im Codebeispiel wird ein alternativer Comparer für Zeichenfolgen mit dem Namen ReverseCompare definiert, der die generische Schnittstelle IComparer<string> (IComparer(Of String) in Visual Basic) implementiert. Der Comparer ruft die CompareTo(String) Methode auf, wobei die Reihenfolge der Vergleiche umgekehrt wird, sodass die Zeichenfolgen anstelle von "niedrig" nach "hoch" sortieren.
Das Codebeispiel erstellt und zeigt ein Array von Dinosauriernamen (die Schlüssel) und ein Array von ganzen Zahlen an, die die maximale Länge jedes Dinosauriers in Metern (die Werte) darstellen. Die Arrays werden dann mehrmals sortiert und angezeigt:
- Die Sort<TKey,TValue>(TKey[], TValue[]) Überladung wird verwendet, um beide Arrays in der Reihenfolge der Dinosauriernamen im ersten Array zu sortieren.
- Die Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) Überladung und eine Instanz von
ReverseComparewerden verwendet, um die Sortierreihenfolge der gekoppelten Arrays umzukehren. - Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) Überladung wird verwendet, um die letzten drei Elemente beider Arrays zu sortieren.
- Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Überladung wird verwendet, um die letzten drei Elemente beider Arrays in umgekehrter Reihenfolge zu sortieren.
Anmerkung
Die Aufrufe der generischen Methoden unterscheiden sich nicht von Aufrufen ihrer nichtgenerischen Entsprechungen, da Visual Basic, C# und C++ den Typ des generischen Typparameters vom Typ der ersten beiden Argumente ableiten. Wenn Sie die Ildasm.exe (IL Disassembler) verwenden, um die Microsoft Zwischensprache (MSIL) zu untersuchen, können Sie sehen, dass die generischen Methoden aufgerufen werden.
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.
Hinweise
Jeder Schlüssel in der Datei keysArray weist ein entsprechendes Element in der itemsArrayDatei auf. Wenn ein Schlüssel während der Sortierung neu positioniert wird, wird das entsprechende Element in der itemsArray Position entsprechend neu positioniert. Daher wird die itemsSortierung nach der Anordnung der entsprechenden Schlüssel in der keysArray.Array
Jeder Schlüssel in der keysArray Muss die IComparable<T> generische Schnittstelle implementieren, um Vergleiche mit jedem anderen Schlüssel zu erhalten.
Sie können sortieren, wenn mehr Elemente als Schlüssel vorhanden sind, aber die Elemente ohne entsprechende Schlüssel werden nicht sortiert. Sie können nicht sortieren, wenn mehr Schlüssel als Elemente vorhanden sind. Dadurch wird ein ArgumentException.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(Protokoll)-Vorgang, bei dem n es sich um einen Length Oarray(n-Protokolln)-Vorgang handelt.
Weitere Informationen
- IComparable<T>
- BinarySearch
- IDictionary<TKey,TValue>
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert ein Objektpaar Array (eins enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Mithilfe der angegebenen IComparer<T> generischen Schnittstelle.
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))
Typparameter
- TKey
Der Typ der Elemente des Schlüsselarrays.
- TValue
Der Typ der Elemente des Elementarrays.
Parameter
- keys
- TKey[]
Die eindimensionale nullbasierte Array , die die zu sortierenden Schlüssel enthält.
- items
- TValue[]
Das eindimensionale, nullbasierte Array Element, das die Elemente enthält, die den Schlüsseln keysentsprechen, oder null nur zu sortieren keys.
- comparer
- IComparer<TKey>
Die IComparer<T> generische Schnittstellenimplementierung, die beim Vergleichen von Elementen verwendet werden soll, oder null um die IComparable<T> generische Schnittstellenimplementierung der einzelnen Elemente zu verwenden.
Ausnahmen
keys ist null.
items ist nicht null, und die untere Grenze von keys nicht mit der unteren Grenze von items.
-oder-
items ist nicht null, und die Länge von keys ist größer als die Länge von items.
-oder-
Die Implementierung, die während der comparer Sortierung einen Fehler verursacht hat. Wenn Sie beispielsweise ein Element mit sich selbst vergleichen, comparer kann "0" nicht zurückgegeben werden.
comparer ist null, und eines oder mehrere Elemente in der keysArray generischen Schnittstelle nicht implementieren IComparable<T> .
Beispiele
Im folgenden Codebeispiel werden die Sort<TKey,TValue>(TKey[], TValue[])Überladungen ,[], Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), und Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generische Methoden zum Sortieren von Arrays veranschaulicht, die Schlüssel und Werte darstellen.
Im Codebeispiel wird ein alternativer Comparer für Zeichenfolgen mit dem Namen ReverseCompare definiert, der die generische Schnittstelle IComparer<string> (IComparer(Of String) in Visual Basic) implementiert. Der Comparer ruft die CompareTo(String) Methode auf, wobei die Reihenfolge der Vergleiche umgekehrt wird, sodass die Zeichenfolgen anstelle von "niedrig" nach "hoch" sortieren.
Das Codebeispiel erstellt und zeigt ein Array von Dinosauriernamen (die Schlüssel) und ein Array von ganzen Zahlen an, die die maximale Länge jedes Dinosauriers in Metern (die Werte) darstellen. Die Arrays werden dann mehrmals sortiert und angezeigt:
- Die Sort<TKey,TValue>(TKey[], TValue[]) Überladung wird verwendet, um beide Arrays in der Reihenfolge der Dinosauriernamen im ersten Array zu sortieren.
- Die Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) Überladung und eine Instanz von
ReverseComparewerden verwendet, um die Sortierreihenfolge der gekoppelten Arrays umzukehren. - Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) Überladung wird verwendet, um die letzten drei Elemente beider Arrays zu sortieren.
- Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Überladung wird verwendet, um die letzten drei Elemente beider Arrays in umgekehrter Reihenfolge zu sortieren.
Anmerkung
Die Aufrufe der generischen Methoden unterscheiden sich nicht von Aufrufen ihrer nichtgenerischen Entsprechungen, da Visual Basic, C# und C++ den Typ des generischen Typparameters vom Typ der ersten beiden Argumente ableiten. Wenn Sie die Ildasm.exe (IL Disassembler) verwenden, um die Microsoft Zwischensprache (MSIL) zu untersuchen, können Sie sehen, dass die generischen Methoden aufgerufen werden.
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.
Hinweise
Jeder Schlüssel in der Datei keysArray weist ein entsprechendes Element in der itemsArrayDatei auf. Wenn ein Schlüssel während der Sortierung neu positioniert wird, wird das entsprechende Element in der itemsArray Position entsprechend neu positioniert. Daher wird die itemsSortierung nach der Anordnung der entsprechenden Schlüssel in der keysArray.Array
Wenn comparer ja null, muss jeder Schlüssel der keysArray generischen Schnittstelle implementieren IComparable<T> , um Vergleiche mit jedem anderen Schlüssel durchführen zu können.
Sie können sortieren, wenn mehr Elemente als Schlüssel vorhanden sind, aber die Elemente ohne entsprechende Schlüssel werden nicht sortiert. Sie können nicht sortieren, wenn mehr Schlüssel als Elemente vorhanden sind. Dadurch wird ein ArgumentException.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(Protokoll)-Vorgang, bei dem n es sich um einen Length Oarray(n-Protokolln)-Vorgang handelt.
Hinweise für Aufrufer
.NET Framework 4 und frühere Versionen verwendeten nur den Quicksort-Algorithmus. Quicksort identifiziert ungültige Vergleiche in einigen Situationen, in denen der Sortiervorgang eine IndexOutOfRangeException Ausnahme auslöst, und löst eine ArgumentException Ausnahme für den Aufrufer aus. Ab .NET Framework 4.5 können Sortiervorgänge, die zuvor ArgumentException ausgelöst haben, keine Ausnahme auslösen, da die Einfüge- und Heapsortalgorithmen keinen ungültigen Vergleich erkennen. Dies gilt größtenteils für Arrays mit weniger als oder gleich 16 Elementen.
Weitere Informationen
- IComparer<T>
- IComparable<T>
- BinarySearch
- Ausführen von Culture-Insensitive Zeichenfolgenvorgängen in Arrays
Gilt für:
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
- Quelle:
- Array.cs
Sortiert einen Bereich von Elementen in einem Objektpaar Array (eines enthält die Schlüssel und der andere enthält die entsprechenden Elemente), basierend auf den Schlüsseln in der ersten Array Mithilfe der IComparable<T> generischen Schnittstellenimplementierung jedes Schlüssels.
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)
Typparameter
- TKey
Der Typ der Elemente des Schlüsselarrays.
- TValue
Der Typ der Elemente des Elementarrays.
Parameter
- keys
- TKey[]
Die eindimensionale nullbasierte Array , die die zu sortierenden Schlüssel enthält.
- items
- TValue[]
Das eindimensionale, nullbasierte Array Element, das die Elemente enthält, die den Schlüsseln keysentsprechen, oder null nur zu sortieren keys.
- index
- Int32
Der Anfangsindex des zu sortierenden Bereichs.
- length
- Int32
Die Anzahl der zu sortierenden Elemente im Bereich.
Ausnahmen
keys ist null.
index ist kleiner als die untere Grenze von keys.
-oder-
length ist kleiner als 0 (null).
items ist nicht null, und die untere Grenze von keys nicht mit der unteren Grenze von items.
-oder-
items ist nicht null, und die Länge von keys ist größer als die Länge von items.
-oder-
index und length geben Sie keinen gültigen Bereich in der keysArray.
-oder-
items ist nicht null, und indexlength geben Sie keinen gültigen Bereich in der itemsArray.
Mindestens ein Element in der keysArray generischen Schnittstelle wird nicht implementiert IComparable<T> .
Beispiele
Im folgenden Codebeispiel werden die Überladungen , Sort<TKey,TValue>(TKey[], TValue[])Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)und Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generische Methoden für das Sortieren von Arrays veranschaulicht, die Schlüssel und Werte darstellen.
Im Codebeispiel wird ein alternativer Comparer für Zeichenfolgen mit dem Namen ReverseCompare definiert, der die generische Schnittstelle IComparer<string> (IComparer(Of String) in Visual Basic) implementiert. Der Comparer ruft die CompareTo(String) Methode auf, wobei die Reihenfolge der Vergleiche umgekehrt wird, sodass die Zeichenfolgen anstelle von "niedrig" nach "hoch" sortieren.
Das Codebeispiel erstellt und zeigt ein Array von Dinosauriernamen (die Schlüssel) und ein Array von ganzen Zahlen an, die die maximale Länge jedes Dinosauriers in Metern (die Werte) darstellen. Die Arrays werden dann mehrmals sortiert und angezeigt:
- Die Sort<TKey,TValue>(TKey[], TValue[]) Überladung wird verwendet, um beide Arrays in der Reihenfolge der Dinosauriernamen im ersten Array zu sortieren.
- Die Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) Überladung und eine Instanz von
ReverseComparewerden verwendet, um die Sortierreihenfolge der gekoppelten Arrays umzukehren. - Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) Überladung wird verwendet, um die letzten drei Elemente beider Arrays zu sortieren.
- Die Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) Überladung wird verwendet, um die letzten drei Elemente beider Arrays in umgekehrter Reihenfolge zu sortieren.
Anmerkung
Die Aufrufe der generischen Methoden unterscheiden sich nicht von Aufrufen ihrer nichtgenerischen Entsprechungen, da Visual Basic, C# und C++ den Typ des generischen Typparameters vom Typ der ersten beiden Argumente ableiten. Wenn Sie die Ildasm.exe (IL Disassembler) verwenden, um die Microsoft Zwischensprache (MSIL) zu untersuchen, können Sie sehen, dass die generischen Methoden aufgerufen werden.
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.
Hinweise
Jeder Schlüssel in der Datei keysArray weist ein entsprechendes Element in der itemsArrayDatei auf. Wenn ein Schlüssel während der Sortierung neu positioniert wird, wird das entsprechende Element in der itemsArray Position entsprechend neu positioniert. Daher wird die itemsSortierung nach der Anordnung der entsprechenden Schlüssel in der keysArray.Array
Jeder Schlüssel innerhalb des angegebenen Elementbereichs in der keysArray muss die IComparable<T> generische Schnittstelle implementieren, um Vergleiche mit jedem anderen Schlüssel durchführen zu können.
Sie können sortieren, wenn mehr Elemente als Schlüssel vorhanden sind, aber die Elemente ohne entsprechende Schlüssel werden nicht sortiert. Sie können nicht sortieren, wenn mehr Schlüssel als Elemente vorhanden sind. Dadurch wird ein ArgumentException.
Wenn die Sortierung nicht erfolgreich abgeschlossen wurde, sind die Ergebnisse nicht definiert.
Diese Methode verwendet den introspektiven Sortieralgorithmus (Introsort) wie folgt:
Wenn die Partitionsgröße kleiner oder gleich 16 Elemente ist, wird ein Einfügesortierungsalgorithmus verwendet.
Wenn die Anzahl der Partitionen 2 * LogN überschreitet, wobei N der Bereich des Eingabearrays ist, wird ein Heapsort-Algorithmus verwendet .
Andernfalls wird ein Quicksort-Algorithmus verwendet.
Diese Implementierung führt eine instabile Sortierung durch; wenn zwei Elemente gleich sind, wird ihre Reihenfolge möglicherweise nicht beibehalten. Im Gegensatz dazu behält eine stabile Sortierung die Reihenfolge von Elementen bei, die gleich sind.
Bei dieser Methode handelt es sich um einen O(n Protokoll n)-Vorgang, wobei n dies der Fall ist length.