Array.Sort<TKey, TValue> Method (TKey[], TValue[], Int32, Int32, IComparer<TKey>)
[ This article is for Windows Phone 8 developers. If you’re developing for Windows 10, see the latest documentation. ]
Sorts a range of elements in a pair of Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the specified IComparer<T> generic interface.
Assembly: mscorlib (in mscorlib.dll)
public static void Sort<TKey, TValue>( TKey[] keys, TValue[] items, int index, int length, IComparer<TKey> comparer )
Type Parameters
- TKey
The type of the elements of the key array.
- TValue
The type of the elements of the items array.
Parameters
- keys
- Type:
TKey
[]
The one-dimensional, zero-based Array that contains the keys to sort.
- items
- Type:
TValue
[]
The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.
- index
- Type: System.Int32
The starting index of the range to sort.
- length
- Type: System.Int32
The number of elements in the range to sort.
- comparer
- Type: System.Collections.Generic.IComparer<TKey>
The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.
| Exception | Condition |
|---|---|
| ArgumentNullException | keys is null. |
| ArgumentOutOfRangeException | index is less than the lower bound of keys. -or- length is less than zero. |
| ArgumentException | items is not null, and the lower bound of keys does not match the lower bound of items. -or- items is not null, and the length of keys is greater than the length of items. -or- index and length do not specify a valid range in the keysArray. -or- items is not null, and index and length do not specify a valid range in the itemsArray. -or- The implementation of comparer caused an error during the sort. For example, comparer might not return 0 when comparing an item with itself. |
| InvalidOperationException | comparer is null, and one or more elements in the keysArray do not implement the IComparable<T> generic interface. |
Each key in the keysArray has a corresponding item in the itemsArray. When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. Therefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.
If comparer is null, each key within the specified range of elements in the keysArray must implement the IComparable<T> generic interface to be capable of comparisons with every other key.
You can sort if there are more items than keys, but the items that have no corresponding keys will not be sorted. You cannot sort if there are more keys than items; doing this throws an ArgumentException.
If the sort is not successfully completed, the results are undefined.
This method uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
On average, this method is an O(n log n) operation, where n is length; in the worst case it is an O(n ^ 2) operation.
The following code example demonstrates the Sort<TKey, TValue>(TKey[], TValue[]), Sort<TKey, TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32), and Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overloads, for sorting pairs of arrays that represent keys and values.
The code example defines an alternative comparer for strings, named ReverseCompare, which implements the IComparer<string> (IComparer(Of String) in Visual Basic, IComparer<String^> in Visual C++) generic interface. The comparer calls the CompareTo(String) method, reversing the order of the comparands so that the strings sort high-to-low instead of low-to-high.
The code example creates and displays an array of dinosaur names (the keys) and an array of integers representing the maximum length of each dinosaur in meters (the values). The arrays are then sorted and displayed several times:
The Sort<TKey, TValue>(TKey[], TValue[]) overload is used to sort both arrays in order of the dinosaur names in the first array.
The Sort<TKey, TValue>(TKey[], TValue[], IComparer<TKey>) overload and an instance of ReverseCompare are used to reverse the sort order of the paired arrays.
The Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32) overload is used to sort the last three elements of both arrays.
The Sort<TKey, TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) overload is used to sort the last three elements of both arrays in reverse order.
Note: |
|---|
The calls to the generic methods do not look any different from calls to their nongeneric counterparts, because Visual Basic, C#, and C++ infer the type of the generic type parameter from the type of the first two arguments. |
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 Demo(System.Windows.Controls.TextBlock outputBlock) { string[] dinosaurs = { "Seismosaurus", "Chasmosaurus", "Coelophysis", "Mamenchisaurus", "Caudipteryx", "Cetiosaurus" }; int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 }; outputBlock.Text += "\n"; for (int i = 0; i < dinosaurs.Length; i++) { outputBlock.Text += String.Format("{0}: up to {1} meters long.", dinosaurs[i], dinosaurSizes[i]) + "\n"; } outputBlock.Text += String.Format("\nSort(dinosaurs, dinosaurSizes)") + "\n"; Array.Sort(dinosaurs, dinosaurSizes); outputBlock.Text += "\n"; for (int i = 0; i < dinosaurs.Length; i++) { outputBlock.Text += String.Format("{0}: up to {1} meters long.", dinosaurs[i], dinosaurSizes[i]) + "\n"; } ReverseComparer rc = new ReverseComparer(); outputBlock.Text += String.Format("\nSort(dinosaurs, dinosaurSizes, rc)") + "\n"; Array.Sort(dinosaurs, dinosaurSizes, rc); outputBlock.Text += "\n"; for (int i = 0; i < dinosaurs.Length; i++) { outputBlock.Text += String.Format("{0}: up to {1} meters long.", dinosaurs[i], dinosaurSizes[i]) + "\n"; } outputBlock.Text += String.Format("\nSort(dinosaurs, dinosaurSizes, 3, 3)") + "\n"; Array.Sort(dinosaurs, dinosaurSizes, 3, 3); outputBlock.Text += "\n"; for (int i = 0; i < dinosaurs.Length; i++) { outputBlock.Text += String.Format("{0}: up to {1} meters long.", dinosaurs[i], dinosaurSizes[i]) + "\n"; } outputBlock.Text += String.Format("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)") + "\n"; Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc); outputBlock.Text += "\n"; for (int i = 0; i < dinosaurs.Length; i++) { outputBlock.Text += String.Format("{0}: up to {1} meters long.", dinosaurs[i], dinosaurSizes[i]) + "\n"; } } } /* 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. */
Note: