Array.Sort Array.Sort Array.Sort Array.Sort Method

定义

对一维数组中的元素进行排序。Sorts the elements in a one-dimensional array.

重载

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

使用指定的 Array,对一维 IComparer 的部分元素进行排序。Sorts the elements in a range of elements in a one-dimensional Array using the specified IComparer.

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

基于第一个 Array 中的关键字,使用指定的 Array,对两个一维 IComparer 对象(一个包含关键字,另一个包含对应的项)的部分元素进行排序。Sorts a range of elements in a pair of one-dimensional 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.

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

使用 Array 中每个元素的 IComparable 实现,对一维 Array 中某部分元素进行排序。Sorts the elements in a range of elements in a one-dimensional Array using the IComparable implementation of each element of the Array.

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

基于第一个 Array 中的关键字,使用每个关键字的 Array 实现,对两个一维 IComparable 对象(一个包含关键字,另一个包含对应的项)的部分元素进行排序。Sorts a range of elements in a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

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

使用指定的 Array,对一维 IComparer 中的元素进行排序。Sorts the elements in a one-dimensional Array using the specified IComparer.

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

基于第一个 Array 中的关键字,使用指定的 Array,对两个一维 IComparer 对象(一个包含关键字,另一个包含对应的项)进行排序。Sorts a pair of one-dimensional 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.

Sort(Array, Array) Sort(Array, Array) Sort(Array, Array) Sort(Array, Array)

基于第一个 Array 中的关键字,使用每个关键字的 Array 实现,对两个一维 IComparable 对象(一个包含关键字,另一个包含对应的项)进行排序。Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

Sort(Array) Sort(Array) Sort(Array)

使用 Array 中每个元素的 IComparable 实现,对整个一维 Array 中的元素进行排序。Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.

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

使用 Array 的每个元素的 IComparable<T> 泛型接口实现,对整个 Array 中的元素进行排序。Sorts the elements in an entire Array using the IComparable<T> generic interface implementation of each element of the Array.

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

使用指定的 Array 泛型接口,对 IComparer<T> 中的元素进行排序。Sorts the elements in an Array using the specified IComparer<T> generic interface.

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

使用指定的 ArrayComparison<T> 中的元素进行排序。Sorts the elements in an Array using the specified Comparison<T>.

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

使用 Array 的每个元素的 IComparable<T> 泛型接口实现,对 Array 中某个元素范围内的元素进行排序。Sorts the elements in a range of elements in an Array using the IComparable<T> generic interface implementation of each element of the Array.

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

使用指定的 Array 泛型接口,对 IComparer<T> 中某个元素范围内的元素进行排序。Sorts the elements in a range of elements in an Array using the specified IComparer<T> generic interface.

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

基于第一个 Array 中的关键字,使用每个关键字的 Array 泛型接口实现,对两个 IComparable<T> 对象(一个包含关键字,另一个包含对应的项)进行排序。Sorts 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 IComparable<T> generic interface implementation of each key.

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

基于第一个 Array 中的关键字,使用指定的 Array 泛型接口,对两个 IComparer<T> 对象(一个包含关键字,另一个包含对应的项)进行排序。Sorts 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.

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

基于第一个 Array 中的关键字,使用每个关键字的 Array 泛型接口实现,对两个 IComparable<T> 对象(一个包含关键字,另一个包含对应的项)的部分元素进行排序。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 IComparable<T> generic interface implementation of each key.

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

基于第一个 Array 中的关键字,使用指定的 Array 泛型接口,对两个 IComparer<T> 对象(一个包含关键字,另一个包含对应的项)的部分元素进行排序。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.

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

使用指定的 Array,对一维 IComparer 的部分元素进行排序。Sorts the elements in a range of elements in a one-dimensional Array using the specified IComparer.

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

参数

array
Array Array Array Array

要排序的一维 ArrayThe one-dimensional Array to sort.

index
Int32 Int32 Int32 Int32

排序范围的起始索引。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

排序范围内的元素数。The number of elements in the range to sort.

comparer
IComparer IComparer IComparer IComparer

比较元素时要使用的 IComparer 实现。The IComparer implementation to use when comparing elements.

- 或 --or- 若为 null,则使用每个元素的 IComparable 实现。null to use the IComparable implementation of each element.

异常

array 是多维的。array is multidimensional.

index 小于 array 的下限。index is less than the lower bound of array.

- 或 --or- length 小于零。length is less than zero.

indexlength 未在 array 中指定有效范围。index and length do not specify a valid range in array.

- 或 --or- comparer 的实现导致排序时出现错误。The implementation of comparer caused an error during the sort. 例如,将某个项与其自身比较时,comparer 可能不返回 0。For example, comparer might not return 0 when comparing an item with itself.

comparernullarray 中的一个或多个元素不实现 IComparable 接口。comparer is null, and one or more elements in array do not implement the IComparable interface.

示例

下面的代码示例演示如何Array使用默认比较器和反向排序顺序的自定义比较器对中的值进行排序。The following code example shows how to sort the values in an Array using the default comparer and a custom comparer that reverses the sort order. 请注意, 结果可能会根据当前CultureInfo情况而有所不同。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class ReverseComparer : IComparer
{
public:
   // Call CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
   }
};

void DisplayValues(array<String^>^ arr)
{
   for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
      Console::WriteLine( "   [{0}] : {1}", i, arr[ i ] );

   Console::WriteLine();
}

int main()
{
   // Create and initialize a new array. and a new custom comparer.
   array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
                             "over","the","lazy","dog" };
   // Instantiate the reverse comparer.
   IComparer^ revComparer = gcnew ReverseComparer();
   
   // Display the values of the Array.
   Console::WriteLine( "The original order of elements in the array:" );
   DisplayValues(words);

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

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

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

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

/* 
This code produces the following output.

The Array initially contains the following values:
   [0] : The
   [1] : QUICK
   [2] : BROWN
   [3] : FOX
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the default comparer:
   [0] : The
   [1] : BROWN
   [2] : FOX
   [3] : QUICK
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the reverse case-insensitive comparer:
   [0] : The
   [1] : QUICK
   [2] : FOX
   [3] : BROWN
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting the entire Array using the default comparer:
   [0] : BROWN
   [1] : dog
   [2] : FOX
   [3] : jumps
   [4] : lazy
   [5] : over
   [6] : QUICK
   [7] : the
   [8] : The

After sorting the entire Array using the reverse case-insensitive comparer:
   [0] : the
   [1] : The
   [2] : QUICK
   [3] : over
   [4] : lazy
   [5] : jumps
   [6] : FOX
   [7] : dog
   [8] : BROWN

*/
using System;
using System.Collections;

public class ReverseComparer : IComparer  
{
   // Call CaseInsensitiveComparer.Compare with the parameters reversed.
   public int Compare(Object x, Object y)  
   {
       return (new CaseInsensitiveComparer()).Compare(y, x );
   }
}

public class Example 
{
   public static void Main()  
   {
      // Create and initialize a new array. 
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps", 
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();
 
      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);
 
      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

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

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

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }
 
   public static void DisplayValues(String[] arr)  
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//    
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN    
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

注解

如果comparernull, 中IComparable array指定范围内的元素中的每个元素都必须实现接口, 以便与中的每个其他元素进行比较。 arrayIf comparer is null, each element within the specified range of elements in array must implement the IComparable interface to be capable of comparisons with every other element in array.

如果排序未成功完成, 则结果是不确定的。If the sort is not successfully completed, the results are undefined.

.NET Framework 包括下表IComparer中列出的预定义的实现。The .NET Framework includes predefined IComparer implementations listed in the following table.

实现Implementation 说明Description
System.Collections.CaseInsensitiveComparer 比较两个对象, 但执行字符串的不区分大小写的比较。Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default 使用当前区域性的排序约定来比较任意两个对象。Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant 使用固定区域性的排序约定来比较两个对象。Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default 使用类型的默认排序T顺序比较类型的两个对象。Compares two objects of type T by using the type's default sort order.

您还可以通过IComparer comparer向参数提供您自己的实现的实例, 支持自定义比较。You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. 该示例通过定义一个ReverseComparer类来为类型的实例反转默认排序顺序并执行不区分大小写的字符串比较, 来实现此目的。The example does this by defining a ReverseComparer class that reverses the default sort order for instances of a type and performs case-insensitive string comparison.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 On (log n) 运算, 其中nlengthFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

调用方说明

.NET Framework 4 及更早版本仅使用快速排序算法。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. 快速排序在某些情况下标识无效的比较器, 其中排序操作IndexOutOfRangeException引发异常, 并向ArgumentException调用方引发异常。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 从开始ArgumentException , 以前引发的排序操作可能不会引发异常, 因为插入排序和 heapsort 算法未检测到无效的比较器。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. 大多数情况下, 这适用于元素少于16个的数组。For the most part, this applies to arrays with fewer than 16 elements.

另请参阅

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

基于第一个 Array 中的关键字,使用指定的 Array,对两个一维 IComparer 对象(一个包含关键字,另一个包含对应的项)的部分元素进行排序。Sorts a range of elements in a pair of one-dimensional 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.

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)

参数

keys
Array Array Array Array

一维 Array,它包含要排序的关键字。The one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

一维 Array,其中包含与 keysArray 中每个关键字对应的项。The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

-or- 如果为 null,则只对 keysArray 进行排序。null to sort only the keysArray.

index
Int32 Int32 Int32 Int32

排序范围的起始索引。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

排序范围内的元素数。The number of elements in the range to sort.

comparer
IComparer IComparer IComparer IComparer

比较元素时要使用的 IComparer 实现。The IComparer implementation to use when comparing elements.

-or- 若为 null,则使用每个元素的 IComparable 实现。null to use the IComparable implementation of each element.

异常

keysArray 是多维的。The keysArray is multidimensional.

- 或 --or- itemsArray 是多维的。The itemsArray is multidimensional.

index 小于 keys 的下限。index is less than the lower bound of keys.

- 或 --or- length 小于零。length is less than zero.

items 不是 null,且 keys 的下限与 items 的下限不匹配。items is not null, and the lower bound of keys does not match the lower bound of items.

- 或 --or- items 不是 null,并且 keys 的长度大于 items 的长度。items is not null, and the length of keys is greater than the length of items.

-or- indexlength 未在 keysArray 中指定有效范围。index and length do not specify a valid range in the keysArray.

- 或 --or- items 不为 null,且 indexlength 未在 itemsArray 中指定有效范围。items is not null, and index and length do not specify a valid range in the itemsArray.

-or- comparer 的实现导致排序时出现错误。The implementation of comparer caused an error during the sort. 例如,将某个项与其自身比较时,comparer 可能不返回 0。For example, comparer might not return 0 when comparing an item with itself.

comparernull,且 keysArray 中的一个或多个元素未实现 IComparable 接口。comparer is null, and one or more elements in the keysArray do not implement the IComparable interface.

示例

下面的代码示例演示如何对两个关联的数组进行排序, 其中第一个数组包含键, 第二个数组包含值。The following code example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. 排序是使用默认比较器和反向排序顺序的自定义比较器来完成的。Sorts are done using the default comparer and a custom comparer that reverses the sort order. 请注意, 结果可能会根据当前CultureInfo情况而有所不同。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

   // Calls CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
   }
};

void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
   for ( int i = 0; i < myKeys->Length; i++ )
   {
      Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
   }
   Console::WriteLine();
}

int main()
{
   // Creates and initializes a new Array and a new custom comparer.
   array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
   array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
   IComparer^ myComparer = gcnew myReverserClass;

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

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

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

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

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

/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

      // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }

   }

   public static void Main()  {
 
      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();
 
      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );
 
      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

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

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

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

   }
 
   public static void PrintKeysAndValues( String[] myKeys, String[] myValues )  {
      for ( int i = 0; i < myKeys.Length; i++ )  {
         Console.WriteLine( "   {0,-10}: {1}", myKeys[i], myValues[i] );
      }
      Console.WriteLine();
   }
}


/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/

Imports System
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 'myReverserClass


   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 'Main


   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 'PrintKeysAndValues

End Class 'SamplesArray


'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

注解

keys中的Array每个键在中items都有相应Array的项。Each key in the keysArray has a corresponding item in the itemsArray. 当在排序过程中重定位某个键时, 中items Array的相应项同样会重新定位。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. items因此, Array会根据中keys相应键的排列顺序对进行排序。 ArrayTherefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

如果comparernull, 则keys 中指定范围内的元素中的每个键都必须实现接口,才能与其他每个键进行比较。Array IComparableIf comparer is null, each key within the specified range of elements in the keysArray must implement the IComparable 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. 如果键比项多, 则无法排序;这样做会引发ArgumentExceptionYou 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.

.NET Framework 包括下表IComparer中列出的预定义的实现。The .NET Framework includes predefined IComparer implementations listed in the following table.

实现Implementation 说明Description
System.Collections.CaseInsensitiveComparer 比较两个对象, 但执行字符串的不区分大小写的比较。Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default 使用当前区域性的排序约定来比较任意两个对象。Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant 使用固定区域性的排序约定来比较两个对象。Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default 使用类型的默认排序T顺序比较类型的两个对象。Compares two objects of type T by using the type's default sort order.

您还可以通过IComparer comparer向参数提供您自己的实现的实例, 支持自定义比较。You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. 该示例通过定义反向默认排序顺序IComparer并执行不区分大小写的字符串比较的自定义实现来实现此目的。The example does this by defining a custom IComparer implementation that reverses the default sort order and performs case-insensitive string comparison.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 On (log n) 运算, 其中nlengthFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

调用方说明

.NET Framework 4 及更早版本仅使用快速排序算法。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. 快速排序在某些情况下标识无效的比较器, 其中排序操作IndexOutOfRangeException引发异常, 并向ArgumentException调用方引发异常。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 从开始ArgumentException , 以前引发的排序操作可能不会引发异常, 因为插入排序和 heapsort 算法未检测到无效的比较器。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. 大多数情况下, 这适用于元素少于16个的数组。For the most part, this applies to arrays with fewer than 16 elements.

另请参阅

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

使用 Array 中每个元素的 IComparable 实现,对一维 Array 中某部分元素进行排序。Sorts the elements in a range of elements in a one-dimensional Array using the IComparable implementation of each element of the 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

参数

array
Array Array Array Array

要排序的一维 ArrayThe one-dimensional Array to sort.

index
Int32 Int32 Int32 Int32

排序范围的起始索引。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

排序范围内的元素数。The number of elements in the range to sort.

异常

array 是多维的。array is multidimensional.

index 小于 array 的下限。index is less than the lower bound of array.

-or- length 小于零。length is less than zero.

indexlength 未在 array 中指定有效范围。index and length do not specify a valid range in array.

array 中的一个或多个元素未实现 IComparable 接口。One or more elements in array do not implement the IComparable interface.

示例

下面的代码示例演示如何Array使用默认比较器和反向排序顺序的自定义比较器对中的值进行排序。The following code example shows how to sort the values in an Array using the default comparer and a custom comparer that reverses the sort order. 请注意, 结果可能会根据当前CultureInfo情况而有所不同。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class ReverseComparer : IComparer
{
public:
   // Call CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
   }
};

void DisplayValues(array<String^>^ arr)
{
   for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
      Console::WriteLine( "   [{0}] : {1}", i, arr[ i ] );

   Console::WriteLine();
}

int main()
{
   // Create and initialize a new array. and a new custom comparer.
   array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
                             "over","the","lazy","dog" };
   // Instantiate the reverse comparer.
   IComparer^ revComparer = gcnew ReverseComparer();
   
   // Display the values of the Array.
   Console::WriteLine( "The original order of elements in the array:" );
   DisplayValues(words);

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

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

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

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

/* 
This code produces the following output.

The Array initially contains the following values:
   [0] : The
   [1] : QUICK
   [2] : BROWN
   [3] : FOX
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the default comparer:
   [0] : The
   [1] : BROWN
   [2] : FOX
   [3] : QUICK
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the reverse case-insensitive comparer:
   [0] : The
   [1] : QUICK
   [2] : FOX
   [3] : BROWN
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting the entire Array using the default comparer:
   [0] : BROWN
   [1] : dog
   [2] : FOX
   [3] : jumps
   [4] : lazy
   [5] : over
   [6] : QUICK
   [7] : the
   [8] : The

After sorting the entire Array using the reverse case-insensitive comparer:
   [0] : the
   [1] : The
   [2] : QUICK
   [3] : over
   [4] : lazy
   [5] : jumps
   [6] : FOX
   [7] : dog
   [8] : BROWN

*/
using System;
using System.Collections;

public class ReverseComparer : IComparer  
{
   // Call CaseInsensitiveComparer.Compare with the parameters reversed.
   public int Compare(Object x, Object y)  
   {
       return (new CaseInsensitiveComparer()).Compare(y, x );
   }
}

public class Example 
{
   public static void Main()  
   {
      // Create and initialize a new array. 
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps", 
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();
 
      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);
 
      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

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

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

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }
 
   public static void DisplayValues(String[] arr)  
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//    
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN    
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

注解

array指定范围内的元素中的每个元素都IComparable必须实现接口, 以便能够与中array的其他每个元素进行比较。Each element within the specified range of elements in array must implement the IComparable interface to be capable of comparisons with every other element in array.

如果排序未成功完成, 则结果是不确定的。If the sort is not successfully completed, the results are undefined.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 On (log n) 运算, 其中nlengthFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

另请参阅

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

基于第一个 Array 中的关键字,使用每个关键字的 Array 实现,对两个一维 IComparable 对象(一个包含关键字,另一个包含对应的项)的部分元素进行排序。Sorts a range of elements in a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

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)

参数

keys
Array Array Array Array

一维 Array,它包含要排序的关键字。The one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

一维 Array,其中包含与 keysArray 中每个关键字对应的项。The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

-or- 如果为 null,则只对 keysArray 进行排序。null to sort only the keysArray.

index
Int32 Int32 Int32 Int32

排序范围的起始索引。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

排序范围内的元素数。The number of elements in the range to sort.

异常

keysArray 是多维的。The keysArray is multidimensional.

- 或 --or- itemsArray 是多维的。The itemsArray is multidimensional.

index 小于 keys 的下限。index is less than the lower bound of keys.

-or- length 小于零。length is less than zero.

items 不为 null,且 keys 的长度大于 items的长度。items is not null, and the length of keys is greater than the length of items.

-or- indexlength 未在 keysArray 中指定有效范围。index and length do not specify a valid range in the keysArray.

-or- items 不为 null,且 indexlength 未在 itemsArray 中指定有效范围。items is not null, and index and length do not specify a valid range in the itemsArray.

keysArray 中的一个或多个元素未实现 IComparable 接口。One or more elements in the keysArray do not implement the IComparable interface.

示例

下面的代码示例演示如何对两个关联的数组进行排序, 其中第一个数组包含键, 第二个数组包含值。The following code example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. 排序是使用默认比较器和反向排序顺序的自定义比较器来完成的。Sorts are done using the default comparer and a custom comparer that reverses the sort order. 请注意, 结果可能会根据当前CultureInfo情况而有所不同。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

   // Calls CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
   }
};

void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
   for ( int i = 0; i < myKeys->Length; i++ )
   {
      Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
   }
   Console::WriteLine();
}

int main()
{
   // Creates and initializes a new Array and a new custom comparer.
   array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
   array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
   IComparer^ myComparer = gcnew myReverserClass;

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

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

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

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

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

/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

      // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }

   }

   public static void Main()  {
 
      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();
 
      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );
 
      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

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

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

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

   }
 
   public static void PrintKeysAndValues( String[] myKeys, String[] myValues )  {
      for ( int i = 0; i < myKeys.Length; i++ )  {
         Console.WriteLine( "   {0,-10}: {1}", myKeys[i], myValues[i] );
      }
      Console.WriteLine();
   }
}


/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/

Imports System
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 'myReverserClass


   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 'Main


   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 'PrintKeysAndValues

End Class 'SamplesArray


'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

注解

keys中的Array每个键在中items都有相应Array的项。Each key in the keysArray has a corresponding item in the itemsArray. 当在排序过程中重定位某个键时, 中items Array的相应项同样会重新定位。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. items因此, Array会根据中keys相应键的排列顺序对进行排序。 ArrayTherefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

keys 指定范围IComparable内的元素中的每个键都必须实现接口,以便能够与其他每个键进行比较。ArrayEach key within the specified range of elements in the keysArray must implement the IComparable 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. 如果键比项多, 则无法排序;这样做会引发ArgumentExceptionYou 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.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 On (log n) 运算, 其中nlengthFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

另请参阅

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

使用指定的 Array,对一维 IComparer 中的元素进行排序。Sorts the elements in a one-dimensional Array using the specified IComparer.

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

参数

array
Array Array Array Array

要排序的一维数组。The one-dimensional array to sort.

comparer
IComparer IComparer IComparer IComparer

比较元素时要使用的实现。The implementation to use when comparing elements.

-or- 若为 null,则使用每个元素的 IComparable 实现。null to use the IComparable implementation of each element.

异常

array 是多维的。array is multidimensional.

comparernullarray 中的一个或多个元素不实现 IComparable 接口。comparer is null, and one or more elements in array do not implement the IComparable interface.

comparer 的实现导致排序时出现错误。The implementation of comparer caused an error during the sort. 例如,将某个项与其自身比较时,comparer 可能不返回 0。For example, comparer might not return 0 when comparing an item with itself.

示例

下面的示例使用默认比较器对字符串数组中的值进行排序。The following example sorts the values in a string array by using the default comparer. 它还定义了一个IComparer名为ReverseComparer的自定义实现, 它在执行不区分大小写的字符串比较时反转对象的默认排序顺序。It also defines a custom IComparer implementation named ReverseComparer that reverses an object's default sort order while performing a case-insensitive string comparison. 请注意, 输出可能因当前区域性而异。Note that the output might vary depending on the current culture.

using namespace System;
using namespace System::Collections;

public ref class ReverseComparer : IComparer
{
public:
   // Call CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
   }
};

void DisplayValues(array<String^>^ arr)
{
   for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
      Console::WriteLine( "   [{0}] : {1}", i, arr[ i ] );

   Console::WriteLine();
}

int main()
{
   // Create and initialize a new array. and a new custom comparer.
   array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
                             "over","the","lazy","dog" };
   // Instantiate the reverse comparer.
   IComparer^ revComparer = gcnew ReverseComparer();
   
   // Display the values of the Array.
   Console::WriteLine( "The original order of elements in the array:" );
   DisplayValues(words);

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

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

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

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

/* 
This code produces the following output.

The Array initially contains the following values:
   [0] : The
   [1] : QUICK
   [2] : BROWN
   [3] : FOX
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the default comparer:
   [0] : The
   [1] : BROWN
   [2] : FOX
   [3] : QUICK
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the reverse case-insensitive comparer:
   [0] : The
   [1] : QUICK
   [2] : FOX
   [3] : BROWN
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting the entire Array using the default comparer:
   [0] : BROWN
   [1] : dog
   [2] : FOX
   [3] : jumps
   [4] : lazy
   [5] : over
   [6] : QUICK
   [7] : the
   [8] : The

After sorting the entire Array using the reverse case-insensitive comparer:
   [0] : the
   [1] : The
   [2] : QUICK
   [3] : over
   [4] : lazy
   [5] : jumps
   [6] : FOX
   [7] : dog
   [8] : BROWN

*/
using System;
using System.Collections;

public class ReverseComparer : IComparer  
{
   // Call CaseInsensitiveComparer.Compare with the parameters reversed.
   public int Compare(Object x, Object y)  
   {
       return (new CaseInsensitiveComparer()).Compare(y, x );
   }
}

public class Example 
{
   public static void Main()  
   {
      // Create and initialize a new array. 
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps", 
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();
 
      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);
 
      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

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

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

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }
 
   public static void DisplayValues(String[] arr)  
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//    
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN    
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

注解

如果comparer arraynull, 则的每个IComparable元素都必须实现接口, 以便与中array的其他每个元素进行比较。If comparer is null, each element of array must implement the IComparable interface to be capable of comparisons with every other element in array.

如果排序未成功完成, 则结果是不确定的。If the sort is not successfully completed, the results are undefined.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 O (n log n) Length运算, 其中n是的arrayFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

.NET Framework 包括下表IComparer中列出的预定义的实现。The .NET Framework includes predefined IComparer implementations listed in the following table.

实现Implementation 说明Description
System.Collections.CaseInsensitiveComparer 比较两个对象, 但执行字符串的不区分大小写的比较。Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default 使用当前区域性的排序约定来比较任意两个对象。Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant 使用固定区域性的排序约定来比较两个对象。Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default 使用类型的默认排序T顺序比较类型的两个对象。Compares two objects of type T by using the type's default sort order.

您还可以通过IComparer comparer向参数提供您自己的实现的实例, 支持自定义比较。You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. 该示例通过定义一个ReverseComparer类来为类型的实例反转默认排序顺序并执行不区分大小写的字符串比较, 来实现此目的。The example does this by defining a ReverseComparer class that reverses the default sort order for instances of a type and performs case-insensitive string comparison.

调用方说明

.NET Framework 4 及更早版本仅使用快速排序算法。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. 快速排序在某些情况下标识无效的比较器, 其中排序操作IndexOutOfRangeException引发异常, 并向ArgumentException调用方引发异常。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 从开始ArgumentException , 以前引发的排序操作可能不会引发异常, 因为插入排序和 heapsort 算法未检测到无效的比较器。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. 大多数情况下, 这适用于元素少于16个的数组。For the most part, this applies to arrays with fewer than 16 elements.

另请参阅

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

基于第一个 Array 中的关键字,使用指定的 Array,对两个一维 IComparer 对象(一个包含关键字,另一个包含对应的项)进行排序。Sorts a pair of one-dimensional 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.

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)

参数

keys
Array Array Array Array

一维 Array,它包含要排序的关键字。The one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

一维 Array,其中包含与 keysArray 中每个关键字对应的项。The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

-or- 如果为 null,则只对 keysArray 进行排序。null to sort only the keysArray.

comparer
IComparer IComparer IComparer IComparer

比较元素时要使用的 IComparer 实现。The IComparer implementation to use when comparing elements.

-or- 若为 null,则使用每个元素的 IComparable 实现。null to use the IComparable implementation of each element.

异常

keysArray 是多维的。The keysArray is multidimensional.

-or- itemsArray 是多维的。The itemsArray is multidimensional.

items 不是 null,并且 keys 的长度大于 items 的长度。items is not null, and the length of keys is greater than the length of items.

-or- comparer 的实现导致排序时出现错误。The implementation of comparer caused an error during the sort. 例如,将某个项与其自身比较时,comparer 可能不返回 0。For example, comparer might not return 0 when comparing an item with itself.

comparernull,且 keysArray 中的一个或多个元素未实现 IComparable 接口。comparer is null, and one or more elements in the keysArray do not implement the IComparable interface.

示例

下面的示例演示如何对两个关联的数组 (其中第一个数组包含键, 第二个数组包含值) 进行排序。The following example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. 排序是使用默认比较器和反向排序顺序的自定义比较器来完成的。Sorts are done using the default comparer and a custom comparer that reverses the sort order. 请注意, 结果可能会根据当前CultureInfo情况而有所不同。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

   // Calls CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
   }
};

void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
   for ( int i = 0; i < myKeys->Length; i++ )
   {
      Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
   }
   Console::WriteLine();
}

int main()
{
   // Creates and initializes a new Array and a new custom comparer.
   array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
   array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
   IComparer^ myComparer = gcnew myReverserClass;

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

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

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

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

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

/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

      // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }

   }

   public static void Main()  {
 
      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();
 
      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );
 
      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

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

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

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

   }
 
   public static void PrintKeysAndValues( String[] myKeys, String[] myValues )  {
      for ( int i = 0; i < myKeys.Length; i++ )  {
         Console.WriteLine( "   {0,-10}: {1}", myKeys[i], myValues[i] );
      }
      Console.WriteLine();
   }
}


/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/

Imports System
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 'myReverserClass


   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 'Main


   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 'PrintKeysAndValues

End Class 'SamplesArray


'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

注解

keys中的Array每个键在中items都有相应Array的项。Each key in the keysArray has a corresponding item in the itemsArray. 当在排序过程中重定位某个键时, 中items Array的相应项同样会重新定位。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. items因此, Array会根据中keys相应键的排列顺序对进行排序。 ArrayTherefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

如果comparer keysnull, 则中的Array每个键都必须实现接口,才能与其他每个IComparable键进行比较。If comparer is null, each key in the keysArray must implement the IComparable 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. 如果键比项多, 则无法排序;这样做会引发ArgumentExceptionYou 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.

.NET Framework 包括下表IComparer中列出的预定义的实现。The .NET Framework includes predefined IComparer implementations listed in the following table.

实现Implementation 说明Description
System.Collections.CaseInsensitiveComparer 比较两个对象, 但执行字符串的不区分大小写的比较。Compares any two objects, but performs a case-insensitive comparison of strings.
Comparer.Default 使用当前区域性的排序约定来比较任意两个对象。Compares any two objects by using the sorting conventions of the current culture.
Comparer.DefaultInvariant 使用固定区域性的排序约定来比较两个对象。Compares any two objects by using the sorting conventions of the invariant culture.
Comparer<T>.Default 使用类型的默认排序T顺序比较类型的两个对象。Compares two objects of type T by using the type's default sort order.

您还可以通过IComparer comparer向参数提供您自己的实现的实例, 支持自定义比较。You can also support custom comparisons by providing an instance of your own IComparer implementation to the comparer parameter. 该示例通过定义一个IComparer实现来反转默认排序顺序并执行不区分大小写的字符串比较, 来实现此目的。The example does this by defining an IComparer implementation that reverses the default sort order and performs case-insensitive string comparison.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 O (n log n) Length运算, 其中n是的keysFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of keys.

调用方说明

.NET Framework 4 及更早版本仅使用快速排序算法。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. 快速排序在某些情况下标识无效的比较器, 其中排序操作IndexOutOfRangeException引发异常, 并向ArgumentException调用方引发异常。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 从开始ArgumentException , 以前引发的排序操作可能不会引发异常, 因为插入排序和 heapsort 算法未检测到无效的比较器。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. 大多数情况下, 这适用于元素少于16个的数组。For the most part, this applies to arrays with fewer than 16 elements.

另请参阅

Sort(Array, Array) Sort(Array, Array) Sort(Array, Array) Sort(Array, Array)

基于第一个 Array 中的关键字,使用每个关键字的 Array 实现,对两个一维 IComparable 对象(一个包含关键字,另一个包含对应的项)进行排序。Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable implementation of each key.

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)

参数

keys
Array Array Array Array

一维 Array,它包含要排序的关键字。The one-dimensional Array that contains the keys to sort.

items
Array Array Array Array

一维 Array,其中包含与 keysArray 中每个关键字对应的项。The one-dimensional Array that contains the items that correspond to each of the keys in the keysArray.

-or- 如果为 null,则只对 keysArray 进行排序。null to sort only the keysArray.

异常

keysArray 是多维的。The keysArray is multidimensional.

-or- itemsArray 是多维的。The itemsArray is multidimensional.

items 不是 null,并且 keys 的长度大于 items 的长度。items is not null, and the length of keys is greater than the length of items.

keysArray 中的一个或多个元素未实现 IComparable 接口。One or more elements in the keysArray do not implement the IComparable interface.

示例

下面的示例演示如何对两个关联的数组 (其中第一个数组包含键, 第二个数组包含值) 进行排序。The following example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. 排序是使用默认比较器和反向排序顺序的自定义比较器来完成的。Sorts are done using the default comparer and a custom comparer that reverses the sort order. 请注意, 结果可能会根据当前CultureInfo情况而有所不同。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class myReverserClass: public IComparer
{
private:

   // Calls CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
   }
};

void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
   for ( int i = 0; i < myKeys->Length; i++ )
   {
      Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
   }
   Console::WriteLine();
}

int main()
{
   // Creates and initializes a new Array and a new custom comparer.
   array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
   array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
   IComparer^ myComparer = gcnew myReverserClass;

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

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

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

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

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

/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/
using System;
using System.Collections;

public class SamplesArray  {
 
   public class myReverserClass : IComparer  {

      // Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      int IComparer.Compare( Object x, Object y )  {
          return( (new CaseInsensitiveComparer()).Compare( y, x ) );
      }

   }

   public static void Main()  {
 
      // Creates and initializes a new Array and a new custom comparer.
      String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
      String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
      IComparer myComparer = new myReverserClass();
 
      // Displays the values of the Array.
      Console.WriteLine( "The Array initially contains the following values:" );
      PrintKeysAndValues( myKeys, myValues );
 
      // Sorts a section of the Array using the default comparer.
      Array.Sort( myKeys, myValues, 1, 3 );
      Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
      PrintKeysAndValues( myKeys, myValues );

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

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

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

   }
 
   public static void PrintKeysAndValues( String[] myKeys, String[] myValues )  {
      for ( int i = 0; i < myKeys.Length; i++ )  {
         Console.WriteLine( "   {0,-10}: {1}", myKeys[i], myValues[i] );
      }
      Console.WriteLine();
   }
}


/* 
This code produces the following output.

The Array initially contains the following values:
   red       : strawberries
   GREEN     : PEARS
   YELLOW    : LIMES
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the default comparer:
   red       : strawberries
   BLUE      : BERRIES
   GREEN     : PEARS
   YELLOW    : LIMES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting a section of the Array using the reverse case-insensitive comparer:
   red       : strawberries
   YELLOW    : LIMES
   GREEN     : PEARS
   BLUE      : BERRIES
   purple    : grapes
   black     : olives
   orange    : cantaloupe

After sorting the entire Array using the default comparer:
   black     : olives
   BLUE      : BERRIES
   GREEN     : PEARS
   orange    : cantaloupe
   purple    : grapes
   red       : strawberries
   YELLOW    : LIMES

After sorting the entire Array using the reverse case-insensitive comparer:
   YELLOW    : LIMES
   red       : strawberries
   purple    : grapes
   orange    : cantaloupe
   GREEN     : PEARS
   BLUE      : BERRIES
   black     : olives

*/

Imports System
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 'myReverserClass


   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 'Main


   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 'PrintKeysAndValues

End Class 'SamplesArray


'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

注解

keys中的Array每个键在中items都有相应Array的项。Each key in the keysArray has a corresponding item in the itemsArray. 当在排序过程中重定位某个键时, 中items Array的相应项同样会重新定位。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. items因此, Array会根据中keys相应键的排列顺序对进行排序。 ArrayTherefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

中的keys Array每个键都必须IComparable实现接口, 才能与其他每个键进行比较。Each key in the keysArray must implement the IComparable 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. 如果键比项多, 则无法排序;这样做会引发ArgumentExceptionYou 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.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 O (n log n) Length运算, 其中n是的keysFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of keys.

另请参阅

Sort(Array) Sort(Array) Sort(Array)

使用 Array 中每个元素的 IComparable 实现,对整个一维 Array 中的元素进行排序。Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.

public:
 static void Sort(Array ^ array);
public static void Sort (Array array);
static member Sort : Array -> unit

参数

array
Array Array Array Array

要排序的一维 ArrayThe one-dimensional Array to sort.

异常

array 是多维的。array is multidimensional.

array 中的一个或多个元素未实现 IComparable 接口。One or more elements in array do not implement the IComparable interface.

示例

下面的代码示例演示如何Array使用默认比较器和反向排序顺序的自定义比较器对中的值进行排序。The following code example shows how to sort the values in an Array using the default comparer and a custom comparer that reverses the sort order. 请注意, 结果可能会根据当前CultureInfo情况而有所不同。Note that the result might vary depending on the current CultureInfo.

using namespace System;
using namespace System::Collections;

public ref class ReverseComparer : IComparer
{
public:
   // Call CaseInsensitiveComparer::Compare with the parameters reversed.
   virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
   {
      return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
   }
};

void DisplayValues(array<String^>^ arr)
{
   for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
      Console::WriteLine( "   [{0}] : {1}", i, arr[ i ] );

   Console::WriteLine();
}

int main()
{
   // Create and initialize a new array. and a new custom comparer.
   array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
                             "over","the","lazy","dog" };
   // Instantiate the reverse comparer.
   IComparer^ revComparer = gcnew ReverseComparer();
   
   // Display the values of the Array.
   Console::WriteLine( "The original order of elements in the array:" );
   DisplayValues(words);

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

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

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

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

/* 
This code produces the following output.

The Array initially contains the following values:
   [0] : The
   [1] : QUICK
   [2] : BROWN
   [3] : FOX
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the default comparer:
   [0] : The
   [1] : BROWN
   [2] : FOX
   [3] : QUICK
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting a section of the Array using the reverse case-insensitive comparer:
   [0] : The
   [1] : QUICK
   [2] : FOX
   [3] : BROWN
   [4] : jumps
   [5] : over
   [6] : the
   [7] : lazy
   [8] : dog

After sorting the entire Array using the default comparer:
   [0] : BROWN
   [1] : dog
   [2] : FOX
   [3] : jumps
   [4] : lazy
   [5] : over
   [6] : QUICK
   [7] : the
   [8] : The

After sorting the entire Array using the reverse case-insensitive comparer:
   [0] : the
   [1] : The
   [2] : QUICK
   [3] : over
   [4] : lazy
   [5] : jumps
   [6] : FOX
   [7] : dog
   [8] : BROWN

*/
using System;
using System.Collections;

public class ReverseComparer : IComparer  
{
   // Call CaseInsensitiveComparer.Compare with the parameters reversed.
   public int Compare(Object x, Object y)  
   {
       return (new CaseInsensitiveComparer()).Compare(y, x );
   }
}

public class Example 
{
   public static void Main()  
   {
      // Create and initialize a new array. 
      String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps", 
                         "over", "the", "lazy", "dog" };
      // Instantiate the reverse comparer.
      IComparer revComparer = new ReverseComparer();
 
      // Display the values of the array.
      Console.WriteLine( "The original order of elements in the array:" );
      DisplayValues(words);
 
      // Sort a section of the array using the default comparer.
      Array.Sort(words, 1, 3);
      Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
      DisplayValues(words);

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

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

      // Sort the entire array by using the reverse case-insensitive comparer.
      Array.Sort(words, revComparer);
      Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
      DisplayValues(words);
   }
 
   public static void DisplayValues(String[] arr)  
   {
      for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
            i++ )  {
         Console.WriteLine( "   [{0}] : {1}", i, arr[i] );
      }
      Console.WriteLine();
   }
}
// The example displays the following output:
//    The original order of elements in the array:
//       [0] : The
//       [1] : QUICK
//       [2] : BROWN
//       [3] : FOX
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the default comparer:
//       [0] : The
//       [1] : BROWN
//       [2] : FOX
//       [3] : QUICK
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting elements 1-3 by using the reverse case-insensitive comparer:
//       [0] : The
//       [1] : QUICK
//       [2] : FOX
//       [3] : BROWN
//       [4] : jumps
//       [5] : over
//       [6] : the
//       [7] : lazy
//       [8] : dog
//    
//    After sorting the entire array by using the default comparer:
//       [0] : BROWN
//       [1] : dog
//       [2] : FOX
//       [3] : jumps
//       [4] : lazy
//       [5] : over
//       [6] : QUICK
//       [7] : the
//       [8] : The
//    
//    After sorting the entire array using the reverse case-insensitive comparer:
//       [0] : the
//       [1] : The
//       [2] : QUICK
//       [3] : over
//       [4] : lazy
//       [5] : jumps
//       [6] : FOX
//       [7] : dog
//       [8] : BROWN    
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

注解

array每个元素都必须IComparable实现接口, 以便与中array的其他每个元素进行比较。Each element of array must implement the IComparable interface to be capable of comparisons with every other element in array.

如果排序未成功完成, 则结果是不确定的。If the sort is not successfully completed, the results are undefined.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 O (n log n) Length运算, 其中n是的arrayFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

另请参阅

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

使用 Array 的每个元素的 IComparable<T> 泛型接口实现,对整个 Array 中的元素进行排序。Sorts the elements in an entire Array using the IComparable<T> generic interface implementation of each element of the 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())

类型参数

T

数组元素的类型。The type of the elements of the array.

参数

array
T[]

要排序的从零开始的一维 ArrayThe one-dimensional, zero-based Array to sort.

异常

array 中的一个或多个元素未实现 IComparable<T> 泛型接口。One or more elements in array do not implement the IComparable<T> generic interface.

示例

下面的代码示例演示Sort<T>(T[])泛型方法重载BinarySearch<T>(T[], T)和泛型方法重载。The following code example demonstrates the Sort<T>(T[]) generic method overload and the BinarySearch<T>(T[], T) generic method overload. 创建一个字符串数组, 无特定顺序。An array of strings is created, in no particular order.

显示、排序并再次显示数组。The array is displayed, sorted, and displayed again.

备注

Sort和泛型方法的BinarySearch调用与对其非泛型方法的调用没有任何区别, 因为 Visual Basic、 C#和C++从第一个参数的类型推断泛型类型参数的类型.The calls to the Sort and BinarySearch 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 argument. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

然后, 使用泛型方法重载搜索两个字符串, 一个字符串不在数组中, 另一个是。 BinarySearch<T>(T[], T)The BinarySearch<T>(T[], T) generic method overload is then used to search for two strings, one that is not in the array and one that is. BinarySearch方法的数组和返回值将传递ShowWhere给泛型方法, 该方法显示索引值 (如果找到该字符串), 否则为搜索字符串在数组中所处的元素。The array and the return value of the BinarySearch method are passed to the ShowWhere generic method, which displays the index value if the string is found, and otherwise the elements the search string would fall between if it were in the array. 如果字符串不是 n 数组, 则该索引为负, 因此该ShowWhere方法采用按位求补 ( C#和中的 ~ 运算符C++, Xor Visual Basic 中为-1) 以获取列表中大于的第一个元素的索引。搜索字符串。The index is negative if the string is not n the array, so the ShowWhere method takes the bitwise complement (the ~ operator in C# and Visual 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 namespace System;
using namespace System::Collections::Generic;

generic<typename T> void ShowWhere(array<T>^ arr, int index)
{
    if (index<0)
    {
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        //
        index = ~index;

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

        if (index == 0)
            Console::Write("beginning of array and ");
        else
            Console::Write("{0} and ", arr[index-1]);

        if (index == arr->Length)
            Console::WriteLine("end of array.");
        else
            Console::WriteLine("{0}.", arr[index]);
    }
    else
    {
        Console::WriteLine("Found at index {0}.", index);
    }
};

void main()
{
    array<String^>^ dinosaurs = {"Pachycephalosaurus", 
                                 "Amargasaurus", 
                                 "Tyrannosaurus", 
                                 "Mamenchisaurus", 
                                 "Deinonychus", 
                                 "Edmontosaurus"};

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nSort");
    Array::Sort(dinosaurs);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nBinarySearch for 'Coelophysis':");
    int index = Array::BinarySearch(dinosaurs, "Coelophysis");
    ShowWhere(dinosaurs, index);

    Console::WriteLine("\nBinarySearch for 'Tyrannosaurus':");
    index = Array::BinarySearch(dinosaurs, "Tyrannosaurus");
    ShowWhere(dinosaurs, index);
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Amargasaurus and Deinonychus.

BinarySearch for 'Tyrannosaurus':
Found at index 5.
 */
using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {"Pachycephalosaurus", 
                              "Amargasaurus", 
                              "Tyrannosaurus", 
                              "Mamenchisaurus", 
                              "Deinonychus", 
                              "Edmontosaurus"};

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nSort");
        Array.Sort(dinosaurs);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nBinarySearch for 'Coelophysis':");
        int index = Array.BinarySearch(dinosaurs, "Coelophysis");
        ShowWhere(dinosaurs, index);

        Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus");
        ShowWhere(dinosaurs, index);
    }

    private static void ShowWhere<T>(T[] array, int index)
    {
        if (index<0)
        {
            // If the index is negative, it represents the bitwise
            // complement of the next larger element in the array.
            //
            index = ~index;

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

            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index-1]);

            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Amargasaurus and Deinonychus.

BinarySearch for 'Tyrannosaurus':
Found at index 5.
 */
Imports System
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.

注解

array每个元素都必须IComparable<T>实现泛型接口, 以便与中array的其他每个元素进行比较。Each element of array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

如果排序未成功完成, 则结果是不确定的。If the sort is not successfully completed, the results are undefined.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 O (n log n) Length运算, 其中n是的arrayFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

另请参阅

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

使用指定的 Array 泛型接口,对 IComparer<T> 中的元素进行排序。Sorts the elements in an Array using the specified IComparer<T> generic interface.

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);
static member Sort : 'T[] * System.Collections.Generic.IComparer<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), comparer As IComparer(Of T))

类型参数

T

数组元素的类型。The type of the elements of the array.

参数

array
T[]

要排序的从零开始的一维 ArrayThe one-dimensional, zero-base Array to sort

comparer
IComparer<T> IComparer<T> IComparer<T> IComparer<T>

比较元素时使用的 IComparer<T> 泛型接口实现;如果为 null,则使用每个元素的 IComparable<T> 泛型接口实现。The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

异常

comparernull,并且 array 中的一个或多个元素未实现 IComparable<T> 泛型接口。comparer is null, and one or more elements in array do not implement the IComparable<T> generic interface.

comparer 的实现导致排序时出现错误。The implementation of comparer caused an error during the sort. 例如,将某个项与其自身比较时,comparer 可能不返回 0。For example, comparer might not return 0 when comparing an item with itself.

示例

下面的代码示例演示Sort<T>(T[], IComparer<T>)泛型方法重载BinarySearch<T>(T[], T, IComparer<T>)和泛型方法重载。The following code example demonstrates the Sort<T>(T[], IComparer<T>) generic method overload and the BinarySearch<T>(T[], T, IComparer<T>) generic method overload.

此代码示例定义了一个名为ReverseCompare的字符串的替代比较器, 该比较器实现了IComparer<string> ( C++IComparer(Of String)在 Visual Basic IComparer<String^>中的 Visual) 泛型接口。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. 比较器调用CompareTo(String)方法, 并反转比较数的顺序, 以便字符串排序为高到低而不是低到高。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 array is displayed, sorted, and displayed again. 若要使用BinarySearch方法, 必须对数组进行排序。Arrays must be sorted in order to use the BinarySearch method.

备注

Sort<T>(T[], IComparer<T>)和泛型方法的BinarySearch<T>(T[], T, IComparer<T>)调用与对其非泛型方法的调用没有任何区别, 因为 Visual Basic、 C#和C++从第一个参数的类型推断泛型类型参数的类型.The calls to the Sort<T>(T[], IComparer<T>) and BinarySearch<T>(T[], T, IComparer<T>) 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 argument. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

然后, 使用泛型方法重载搜索两个字符串, 一个字符串不在数组中, 另一个是。 BinarySearch<T>(T[], T, IComparer<T>)The BinarySearch<T>(T[], T, IComparer<T>) generic method overload is then used to search for two strings, one that is not in the array and one that is. BinarySearch<T>(T[], T, IComparer<T>)方法的数组和返回值将传递ShowWhere给泛型方法, 该方法显示索引值 (如果找到该字符串), 否则为搜索字符串在数组中所处的元素。The array and the return value of the BinarySearch<T>(T[], T, IComparer<T>) method are passed to the ShowWhere generic method, which displays the index value if the string is found, and otherwise the elements the search string would fall between if it were in the array. 如果字符串不是 n 数组, 则该索引为负, 因此该ShowWhere方法采用按位求补 ( C#和中的 ~ 运算符C++, Xor Visual Basic 中为-1) 以获取列表中大于的第一个元素的索引。搜索字符串。The index is negative if the string is not n the array, so the ShowWhere method takes the bitwise complement (the ~ operator in C# and Visual 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 namespace System;
using namespace System::Collections::Generic;

public ref class ReverseComparer: IComparer<String^>
{
public:
    virtual int Compare(String^ x, String^ y)
    {
        // Compare y and x in reverse order.
        return y->CompareTo(x);
    }
};

generic<typename T> void ShowWhere(array<T>^ arr, int index)
{
    if (index<0)
    {
        // If the index is negative, it represents the bitwise
        // complement of the next larger element in the array.
        //
        index = ~index;

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

        if (index == 0)
            Console::Write("beginning of array and ");
        else
            Console::Write("{0} and ", arr[index-1]);

        if (index == arr->Length)
            Console::WriteLine("end of array.");
        else
            Console::WriteLine("{0}.", arr[index]);
    }
    else
    {
        Console::WriteLine("Found at index {0}.", index);
    }
};

void main()
{
    array<String^>^ dinosaurs = {"Pachycephalosaurus", 
                                 "Amargasaurus", 
                                 "Tyrannosaurus", 
                                 "Mamenchisaurus", 
                                 "Deinonychus", 
                                 "Edmontosaurus"};

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

    Console::WriteLine("\nSort");
    Array::Sort(dinosaurs, rc);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nBinarySearch for 'Coelophysis':");
    int index = Array::BinarySearch(dinosaurs, "Coelophysis", rc);
    ShowWhere(dinosaurs, index);

    Console::WriteLine("\nBinarySearch for 'Tyrannosaurus':");
    index = Array::BinarySearch(dinosaurs, "Tyrannosaurus", rc);
    ShowWhere(dinosaurs, index);
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Deinonychus and Amargasaurus.

BinarySearch for 'Tyrannosaurus':
Found at index 0.
 */
using System;
using System.Collections.Generic;

public class ReverseComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        // Compare y and x in reverse order.
        return y.CompareTo(x);
    }
}

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {"Pachycephalosaurus", 
                              "Amargasaurus", 
                              "Tyrannosaurus", 
                              "Mamenchisaurus", 
                              "Deinonychus", 
                              "Edmontosaurus"};

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort");
        Array.Sort(dinosaurs, rc);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nBinarySearch for 'Coelophysis':");
        int index = Array.BinarySearch(dinosaurs, "Coelophysis", rc);
        ShowWhere(dinosaurs, index);

        Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
        index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc);
        ShowWhere(dinosaurs, index);
    }

    private static void ShowWhere<T>(T[] array, int index)
    {
        if (index<0)
        {
            // If the index is negative, it represents the bitwise
            // complement of the next larger element in the array.
            //
            index = ~index;

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

            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index-1]);

            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus

Sort

Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus

BinarySearch for 'Coelophysis':
Not found. Sorts between: Deinonychus and Amargasaurus.

BinarySearch for 'Tyrannosaurus':
Found at index 0.
 */
Imports System
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.

注解

如果comparer arraynull, 则的每个IComparable<T>元素都必须实现泛型接口, 以便与中array的其他每个元素进行比较。If comparer is null, each element of array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

如果排序未成功完成, 则结果是不确定的。If the sort is not successfully completed, the results are undefined.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 O (n log n) Length运算, 其中n是的arrayFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

调用方说明

.NET Framework 4 及更早版本仅使用快速排序算法。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. 快速排序在某些情况下标识无效的比较器, 其中排序操作IndexOutOfRangeException引发异常, 并向ArgumentException调用方引发异常。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 从开始ArgumentException , 以前引发的排序操作可能不会引发异常, 因为插入排序和 heapsort 算法未检测到无效的比较器。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. 大多数情况下, 这适用于元素少于16个的数组。For the most part, this applies to arrays with fewer than 16 elements.

另请参阅

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

使用指定的 ArrayComparison<T> 中的元素进行排序。Sorts the elements in an Array using the specified 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))

类型参数

T

数组元素的类型。The type of the elements of the array.

参数

array
T[]

要排序的从零开始的一维 ArrayThe one-dimensional, zero-based Array to sort

comparison
Comparison<T> Comparison<T> Comparison<T> Comparison<T>

比较元素时要使用的 Comparison<T>The Comparison<T> to use when comparing elements.

异常

arraynullarray is null.

-or- comparisonnullcomparison is null.

comparison 的实现导致排序时出现错误。The implementation of comparison caused an error during the sort. 例如,将某个项与其自身比较时,comparison 可能不返回 0。For example, comparison might not return 0 when comparing an item with itself.

示例

下面的代码示例演示Sort(Comparison<T>)方法重载。The following code example demonstrates the Sort(Comparison<T>) method overload.

此代码示例定义了一个名为CompareDinosByLength的字符串的替代比较方法。The code example defines an alternative comparison method for strings, named CompareDinosByLength. 此方法的工作方式如下:首先, 对这些比较的值null进行测试, 并将空引用视为小于非空引用。This method works as follows: First, the comparands are tested fornull, and a null reference is treated as less than a non-null. 其次, 比较字符串长度, 较长的字符串被认为更大。Second, the string lengths are compared, and the longer string is deemed to be greater. 第三, 如果长度相等, 则使用普通字符串比较。Third, if the lengths are equal, ordinary string comparison is used.

创建一个字符串数组, 并以无特定顺序填充四个字符串。A array of strings is created and populated with four strings, in no particular order. 此列表还包括一个空字符串和一个空引用。The list also includes an empty string and a null reference. 显示列表, 使用Comparison<T> CompareDinosByLength表示方法的泛型委托进行排序, 并再次显示。The list is displayed, sorted using a Comparison<T> generic delegate representing the CompareDinosByLength method, and displayed again.

using namespace System;
using namespace System::Collections::Generic;

int CompareDinosByLength(String^ x, String^ y)
{
    if (x == nullptr)
    {
        if (y == nullptr)
        {
            // If x is null and y is null, they're
            // equal. 
            return 0;
        }
        else
        {
            // If x is null and y is not null, y
            // is greater. 
            return -1;
        }
    }
    else
    {
        // If x is not null...
        //
        if (y == nullptr)
            // ...and y is null, x is greater.
        {
            return 1;
        }
        else
        {
            // ...and y is not null, compare the 
            // lengths of the two strings.
            //
            int retval = x->Length.CompareTo(y->Length);

            if (retval != 0)
            {
                // If the strings are not of equal length,
                // the longer string is greater.
                //
                return retval;
            }
            else
            {
                // If the strings are of equal length,
                // sort them with ordinary string comparison.
                //
                return x->CompareTo(y);
            }
        }
    }
};

void Display(array<String^>^ arr)
{
    Console::WriteLine();
    for each(String^ s in arr)
    {
        if (s == nullptr)
            Console::WriteLine("(null)");
        else
            Console::WriteLine("\"{0}\"", s);
    }
};

void main()
{
    array<String^>^ dinosaurs = { 
        "Pachycephalosaurus",
        "Amargasaurus",
        "",
        nullptr,
        "Mamenchisaurus",
        "Deinonychus" };
    Display(dinosaurs);

    Console::WriteLine("\nSort with generic Comparison<String^> delegate:");
    Array::Sort(dinosaurs,
        gcnew Comparison<String^>(CompareDinosByLength));
    Display(dinosaurs);

}

/* This code example produces the following output:

"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"

Sort with generic Comparison<String^> delegate:

(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
 */
using System;
using System.Collections.Generic;

public class Example
{
    private static int CompareDinosByLength(string x, string y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're
                // equal. 
                return 0;
            }
            else
            {
                // If x is null and y is not null, y
                // is greater. 
                return -1;
            }
        }
        else
        {
            // If x is not null...
            //
            if (y == null)
                // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                // ...and y is not null, compare the 
                // lengths of the two strings.
                //
                int retval = x.Length.CompareTo(y.Length);

                if (retval != 0)
                {
                    // If the strings are not of equal length,
                    // the longer string is greater.
                    //
                    return retval;
                }
                else
                {
                    // If the strings are of equal length,
                    // sort them with ordinary string comparison.
                    //
                    return x.CompareTo(y);
                }
            }
        }
    }

    public static void Main()
    {
        string[] dinosaurs = {
            "Pachycephalosaurus",
            "Amargasaurus",
            "",
            null,
            "Mamenchisaurus",
            "Deinonychus" };
        Display(dinosaurs);

        Console.WriteLine("\nSort with generic Comparison<string> delegate:");
        Array.Sort(dinosaurs, CompareDinosByLength);
        Display(dinosaurs);

    }

    private static void Display(string[] arr)
    {
        Console.WriteLine();
        foreach( string s in arr )
        {
            if (s == null)
                Console.WriteLine("(null)");
            else
                Console.WriteLine("\"{0}\"", s);
        }
    }
}

/* This code example produces the following output:

"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"

Sort with generic Comparison<string> delegate:

(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
 */
Imports System
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"

注解

如果排序未成功完成, 则结果是不确定的。If the sort is not successfully completed, the results are undefined.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 O (n log n) Length运算, 其中n是的arrayFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

调用方说明

.NET Framework 4 及更早版本仅使用快速排序算法。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. 快速排序在某些情况下标识无效的比较器, 其中排序操作IndexOutOfRangeException引发异常, 并向ArgumentException调用方引发异常。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 从开始ArgumentException , 以前引发的排序操作可能不会引发异常, 因为插入排序和 heapsort 算法未检测到无效的比较器。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. 大多数情况下, 这适用于元素少于16个的数组。For the most part, this applies to arrays with fewer than 16 elements.

另请参阅

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

使用 Array 的每个元素的 IComparable<T> 泛型接口实现,对 Array 中某个元素范围内的元素进行排序。Sorts the elements in a range of elements in an Array using the IComparable<T> generic interface implementation of each element of the 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)

类型参数

T

数组元素的类型。The type of the elements of the array.

参数

array
T[]

要排序的从零开始的一维 ArrayThe one-dimensional, zero-based Array to sort

index
Int32 Int32 Int32 Int32

排序范围的起始索引。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

排序范围内的元素数。The number of elements in the range to sort.

异常

index 小于 array 的下限。index is less than the lower bound of array.

-or- length 小于零。length is less than zero.

indexlength 未在 array 中指定有效范围。index and length do not specify a valid range in array.

array 中的一个或多个元素未实现 IComparable<T> 泛型接口。One or more elements in array do not implement the IComparable<T> generic interface.

示例

下面的代码示例演示Sort<T>(T[], Int32, Int32)泛型方法重载Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) , 以及用于对数组中的范围进行排序的泛型方法重载。The following code example demonstrates the Sort<T>(T[], Int32, Int32) generic method overload and the Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overload for sorting a range in an array.

此代码示例定义了一个名为ReverseCompare的字符串的替代比较器, 该比较器实现了IComparer<string> ( C++IComparer(Of String)在 Visual Basic IComparer<String^>中的 Visual) 泛型接口。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. 比较器调用CompareTo(String)方法, 并反转比较数的顺序, 以便字符串排序为高到低而不是低到高。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.

此代码示例创建并显示一个恐龙名称数组, 其中包含三个 herbivores, 后跟三个 carnivores (tyrannosaurids)。The code example creates and displays an array of dinosaur names, consisting of three herbivores followed by three carnivores (tyrannosaurids, to be precise). Sort<T>(T[], Int32, Int32)泛型方法重载用于对数组中最后三个元素进行排序, 然后将显示该元素。The Sort<T>(T[], Int32, Int32) generic method overload is used to sort the last three elements of the array, which is then displayed. 泛型方法重载ReverseCompare用于将最后三个元素按相反的顺序进行排序。 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)The Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overload is used with ReverseCompare to sort the last three elements in reverse order. 将再次显示完全混淆的恐龙。The thoroughly confused dinosaurs are displayed again.

备注

Sort<T>(T[], IComparer<T>)和泛型方法的BinarySearch<T>(T[], T, IComparer<T>)调用与对其非泛型方法的调用没有任何区别, 因为 Visual Basic、 C#和C++从第一个参数的类型推断泛型类型参数的类型.The calls to the Sort<T>(T[], IComparer<T>) and BinarySearch<T>(T[], T, IComparer<T>) 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 argument. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

using namespace System;
using namespace System::Collections::Generic;

public ref class ReverseComparer: IComparer<String^>
{
public:
    virtual int Compare(String^ x, String^ y)
    {
        // Compare y and x in reverse order.
        return y->CompareTo(x);
    }
};

void main()
{
    array<String^>^ dinosaurs = {"Pachycephalosaurus", 
                                 "Amargasaurus", 
                                 "Mamenchisaurus",
                                 "Tarbosaurus",
                                 "Tyrannosaurus", 
                                 "Albertasaurus"};

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nSort(dinosaurs, 3, 3)");
    Array::Sort(dinosaurs, 3, 3);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

    Console::WriteLine("\nSort(dinosaurs, 3, 3, rc)");
    Array::Sort(dinosaurs, 3, 3, rc);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
using System;
using System.Collections.Generic;

public class ReverseComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        // Compare y and x in reverse order.
        return y.CompareTo(x);
    }
}

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {"Pachycephalosaurus", 
                              "Amargasaurus", 
                              "Mamenchisaurus", 
                              "Tarbosaurus",
                              "Tyrannosaurus", 
                              "Albertasaurus"};

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nSort(dinosaurs, 3, 3)");
        Array.Sort(dinosaurs, 3, 3);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort(dinosaurs, 3, 3, rc)");
        Array.Sort(dinosaurs, 3, 3, rc);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
Imports System
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

注解

array指定范围内的元素中的每个元素都IComparable<T>必须实现泛型接口, 以便能够与中array的每个其他元素进行比较。Each element within the specified range of elements in array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

如果排序未成功完成, 则结果是不确定的。If the sort is not successfully completed, the results are undefined.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 On (log n) 运算, 其中nlengthFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

另请参阅

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

使用指定的 Array 泛型接口,对 IComparer<T> 中某个元素范围内的元素进行排序。Sorts the elements in a range of elements in an Array using the specified IComparer<T> generic interface.

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

类型参数

T

数组元素的类型。The type of the elements of the array.

参数

array
T[]

要排序的从零开始的一维 ArrayThe one-dimensional, zero-based Array to sort.

index
Int32 Int32 Int32 Int32

排序范围的起始索引。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

排序范围内的元素数。The number of elements in the range to sort.

comparer
IComparer<T> IComparer<T> IComparer<T> IComparer<T>

比较元素时使用的 IComparer<T> 泛型接口实现;如果为 null,则使用每个元素的 IComparable<T> 泛型接口实现。The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

异常

index 小于 array 的下限。index is less than the lower bound of array.

-or- length 小于零。length is less than zero.

indexlength 未在 array 中指定有效范围。index and length do not specify a valid range in array.

-or- comparer 的实现导致排序时出现错误。The implementation of comparer caused an error during the sort. 例如,将某个项与其自身比较时,comparer 可能不返回 0。For example, comparer might not return 0 when comparing an item with itself.

comparernull,并且 array 中的一个或多个元素未实现 IComparable<T> 泛型接口。comparer is null, and one or more elements in array do not implement the IComparable<T> generic interface.

示例

下面的代码示例演示Sort<T>(T[], Int32, Int32)泛型方法重载Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) , 以及用于对数组中的范围进行排序的泛型方法重载。The following code example demonstrates the Sort<T>(T[], Int32, Int32) generic method overload and the Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overload for sorting a range in an array.

此代码示例定义了一个名为ReverseCompare的字符串的替代比较器, 该比较器实现了IComparer<string> ( C++IComparer(Of String)在 Visual Basic IComparer<String^>中的 Visual) 泛型接口。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. 比较器调用CompareTo(String)方法, 并反转比较数的顺序, 以便字符串排序为高到低而不是低到高。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.

此代码示例创建并显示一个恐龙名称数组, 其中包含三个 herbivores, 后跟三个 carnivores (tyrannosaurids)。The code example creates and displays an array of dinosaur names, consisting of three herbivores followed by three carnivores (tyrannosaurids, to be precise). Sort<T>(T[], Int32, Int32)泛型方法重载用于对数组中最后三个元素进行排序, 然后将显示该元素。The Sort<T>(T[], Int32, Int32) generic method overload is used to sort the last three elements of the array, which is then displayed. 泛型方法重载ReverseCompare用于将最后三个元素按相反的顺序进行排序。 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)The Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overload is used with ReverseCompare to sort the last three elements in reverse order. 将再次显示完全混淆的恐龙。The thoroughly confused dinosaurs are displayed again.

备注

Sort<T>(T[], IComparer<T>)和泛型方法的BinarySearch<T>(T[], T, IComparer<T>)调用与对其非泛型方法的调用没有任何区别, 因为 Visual Basic、 C#和C++从第一个参数的类型推断泛型类型参数的类型.The calls to the Sort<T>(T[], IComparer<T>) and BinarySearch<T>(T[], T, IComparer<T>) 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 argument. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

using namespace System;
using namespace System::Collections::Generic;

public ref class ReverseComparer: IComparer<String^>
{
public:
    virtual int Compare(String^ x, String^ y)
    {
        // Compare y and x in reverse order.
        return y->CompareTo(x);
    }
};

void main()
{
    array<String^>^ dinosaurs = {"Pachycephalosaurus", 
                                 "Amargasaurus", 
                                 "Mamenchisaurus",
                                 "Tarbosaurus",
                                 "Tyrannosaurus", 
                                 "Albertasaurus"};

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    Console::WriteLine("\nSort(dinosaurs, 3, 3)");
    Array::Sort(dinosaurs, 3, 3);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

    Console::WriteLine("\nSort(dinosaurs, 3, 3, rc)");
    Array::Sort(dinosaurs, 3, 3, rc);

    Console::WriteLine();
    for each(String^ dinosaur in dinosaurs)
    {
        Console::WriteLine(dinosaur);
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
using System;
using System.Collections.Generic;

public class ReverseComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        // Compare y and x in reverse order.
        return y.CompareTo(x);
    }
}

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {"Pachycephalosaurus", 
                              "Amargasaurus", 
                              "Mamenchisaurus", 
                              "Tarbosaurus",
                              "Tyrannosaurus", 
                              "Albertasaurus"};

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine("\nSort(dinosaurs, 3, 3)");
        Array.Sort(dinosaurs, 3, 3);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort(dinosaurs, 3, 3, rc)");
        Array.Sort(dinosaurs, 3, 3, rc);

        Console.WriteLine();
        foreach( string dinosaur in dinosaurs )
        {
            Console.WriteLine(dinosaur);
        }
    }
}

/* This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus

Sort(dinosaurs, 3, 3)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus

Sort(dinosaurs, 3, 3, rc)

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
 */
Imports System
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

注解

如果comparer arraynull, 则中指定范围内的IComparable<T>元素中的每个元素都必须实现泛型接口, 以便能够与中array的每个其他元素进行比较。If comparer is null, each element within the specified range of elements in array must implement the IComparable<T> generic interface to be capable of comparisons with every other element in array.

如果排序未成功完成, 则结果是不确定的。If the sort is not successfully completed, the results are undefined.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 On (log n) 运算, 其中nlengthFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

调用方说明

.NET Framework 4 及更早版本仅使用快速排序算法。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. 快速排序在某些情况下标识无效的比较器, 其中排序操作IndexOutOfRangeException引发异常, 并向ArgumentException调用方引发异常。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 从开始ArgumentException , 以前引发的排序操作可能不会引发异常, 因为插入排序和 heapsort 算法未检测到无效的比较器。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. 大多数情况下, 这适用于元素少于16个的数组。For the most part, this applies to arrays with fewer than 16 elements.

另请参阅

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

基于第一个 Array 中的关键字,使用每个关键字的 Array 泛型接口实现,对两个 IComparable<T> 对象(一个包含关键字,另一个包含对应的项)进行排序。Sorts 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 IComparable<T> generic interface implementation of each key.

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);
static member Sort : 'Key[] * 'Value[] -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue())

类型参数

TKey

关键字数组元素的类型。The type of the elements of the key array.

TValue

项数组元素的类型。The type of the elements of the items array.

参数

keys
TKey[]

从零开始的一维 Array,它包含要排序的关键字。The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

从零开始的一维 Array,其中包含与 keys 中的关键字对应的项;如果为 null,则只对 keys 进行排序。The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

异常

items 不为 null,且 keys 的下限与 items的下限不匹配。items is not null, and the lower bound of keys does not match the lower bound of items.

-or- items 不是 null,并且 keys 的长度大于 items 的长度。items is not null, and the length of keys is greater than the length of items.

keysArray 中的一个或多个元素不实现 IComparable<T> 泛型接口。One or more elements in the keysArray do not implement the IComparable<T> generic interface.

示例

下面的代码示例演示了Sort<TKey,TValue>(TKey[], TValue[])Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)泛型方法重载, 用于对表示键和值的数组对进行排序。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.

此代码示例定义了一个名为ReverseCompare的字符串的替代比较器, 该比较器实现了IComparer<string> ( C++IComparer(Of String)在 Visual Basic IComparer<String^>中的 Visual) 泛型接口。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. 比较器调用CompareTo(String)方法, 并反转比较数的顺序, 以便字符串排序为高到低而不是低到高。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:

备注

对泛型方法的调用与对它们的非泛型方法的调用没有任何不同之处, 因为C#Visual Basic、 C++和从前两个自变量的类型推断泛型类型参数的类型。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. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

using namespace System;
using namespace System::Collections::Generic;

public ref class ReverseComparer: IComparer<String^>
{
public:
    virtual int Compare(String^ x, String^ y)
    {
        // Compare y and x in reverse order.
        return y->CompareTo(x);
    }
};

void main()
{
    array<String^>^ dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

    array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes)");
    Array::Sort(dinosaurs, dinosaurSizes);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
    Array::Sort(dinosaurs, dinosaurSizes, rc);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
    Array::Sort(dinosaurs, dinosaurSizes, 3, 3);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
    Array::Sort(dinosaurs, dinosaurSizes, 3, 3, rc);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
using System;
using System.Collections.Generic;

public class ReverseComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        // Compare y and x in reverse order.
        return y.CompareTo(x);
    }
}

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

        int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes)");
        Array.Sort(dinosaurs, dinosaurSizes);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
        Array.Sort(dinosaurs, dinosaurSizes, rc);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
Imports System
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.

注解

keys中的Array每个键在中items都有相应Array的项。Each key in the keysArray has a corresponding item in the itemsArray. 当在排序过程中重定位某个键时, 中items Array的相应项同样会重新定位。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. items因此, Array会根据中keys相应键的排列顺序对进行排序。 ArrayTherefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

中的keys Array每个键都必须IComparable<T>实现泛型接口, 才能与其他每个键进行比较。Each key 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. 如果键比项多, 则无法排序;这样做会引发ArgumentExceptionYou 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.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 O (n log n) Length运算, 其中n是的arrayFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

另请参阅

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

基于第一个 Array 中的关键字,使用指定的 Array 泛型接口,对两个 IComparer<T> 对象(一个包含关键字,另一个包含对应的项)进行排序。Sorts 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.

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

类型参数

TKey

关键字数组元素的类型。The type of the elements of the key array.

TValue

项数组元素的类型。The type of the elements of the items array.

参数

keys
TKey[]

从零开始的一维 Array,它包含要排序的关键字。The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

从零开始的一维 Array,其中包含与 keys 中的关键字对应的项;如果为 null,则只对 keys 进行排序。The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

comparer
IComparer<TKey>

比较元素时使用的 IComparer<T> 泛型接口实现;如果为 null,则使用每个元素的 IComparable<T> 泛型接口实现。The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

异常

items 不为 null,且 keys 的下限与 items的下限不匹配。items is not null, and the lower bound of keys does not match the lower bound of items.

-or- items 不是 null,并且 keys 的长度大于 items 的长度。items is not null, and the length of keys is greater than the length of items.

-or- comparer 的实现导致排序时出现错误。The implementation of comparer caused an error during the sort. 例如,将某个项与其自身比较时,comparer 可能不返回 0。For example, comparer might not return 0 when comparing an item with itself.

comparernull,且 keysArray 中的一个或多个元素未实现 IComparable<T> 泛型接口。comparer is null, and one or more elements in the keysArray do not implement the IComparable<T> generic interface.

示例

下面的代码示例演示了Sort<TKey,TValue>(TKey[], TValue[]), [], TValue<x: system.object% 60% 602% 28% 60% 600% 5b% 5d% 2c% 60% 601% 5b% 5d% 2csystem.string, IComparer% 7b% 60% 600% 7d% 29 >,Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32),和Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)泛型方法重载, 用于对表示键和值的数组对进行排序。The following code example demonstrates the Sort<TKey,TValue>(TKey[], TValue[]), [], TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Collections.Generic.IComparer%7B%60%600%7D%29>,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.

此代码示例定义了一个名为ReverseCompare的字符串的替代比较器, 该比较器实现了IComparer<string> ( C++IComparer(Of String)在 Visual Basic IComparer<String^>中的 Visual) 泛型接口。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. 比较器调用CompareTo(String)方法, 并反转比较数的顺序, 以便字符串排序为高到低而不是低到高。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:

备注

对泛型方法的调用与对它们的非泛型方法的调用没有任何不同之处, 因为C#Visual Basic、 C++和从前两个自变量的类型推断泛型类型参数的类型。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. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

using namespace System;
using namespace System::Collections::Generic;

public ref class ReverseComparer: IComparer<String^>
{
public:
    virtual int Compare(String^ x, String^ y)
    {
        // Compare y and x in reverse order.
        return y->CompareTo(x);
    }
};

void main()
{
    array<String^>^ dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

    array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes)");
    Array::Sort(dinosaurs, dinosaurSizes);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
    Array::Sort(dinosaurs, dinosaurSizes, rc);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
    Array::Sort(dinosaurs, dinosaurSizes, 3, 3);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
    Array::Sort(dinosaurs, dinosaurSizes, 3, 3, rc);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
using System;
using System.Collections.Generic;

public class ReverseComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        // Compare y and x in reverse order.
        return y.CompareTo(x);
    }
}

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

        int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes)");
        Array.Sort(dinosaurs, dinosaurSizes);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
        Array.Sort(dinosaurs, dinosaurSizes, rc);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
Imports System
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.

注解

keys中的Array每个键在中items都有相应Array的项。Each key in the keysArray has a corresponding item in the itemsArray. 当在排序过程中重定位某个键时, 中items Array的相应项同样会重新定位。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. items因此, Array会根据中keys相应键的排列顺序对进行排序。 ArrayTherefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

如果comparer keysnull, 则中的Array每个键都必须实现泛型接口,才能与其他每个IComparable<T>键进行比较。If comparer is null, each key 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. 如果键比项多, 则无法排序;这样做会引发ArgumentExceptionYou 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.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 O (n log n) Length运算, 其中n是的arrayFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is the Length of array.

调用方说明

.NET Framework 4 及更早版本仅使用快速排序算法。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. 快速排序在某些情况下标识无效的比较器, 其中排序操作IndexOutOfRangeException引发异常, 并向ArgumentException调用方引发异常。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 从开始ArgumentException , 以前引发的排序操作可能不会引发异常, 因为插入排序和 heapsort 算法未检测到无效的比较器。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. 大多数情况下, 这适用于元素少于16个的数组。For the most part, this applies to arrays with fewer than 16 elements.

另请参阅

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

基于第一个 Array 中的关键字,使用每个关键字的 Array 泛型接口实现,对两个 IComparable<T> 对象(一个包含关键字,另一个包含对应的项)的部分元素进行排序。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 IComparable<T> generic interface implementation of each key.

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

类型参数

TKey

关键字数组元素的类型。The type of the elements of the key array.

TValue

项数组元素的类型。The type of the elements of the items array.

参数

keys
TKey[]

从零开始的一维 Array,它包含要排序的关键字。The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

从零开始的一维 Array,其中包含与 keys 中的关键字对应的项;如果为 null,则只对 keys 进行排序。The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

index
Int32 Int32 Int32 Int32

排序范围的起始索引。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

排序范围内的元素数。The number of elements in the range to sort.

异常

index 小于 keys 的下限。index is less than the lower bound of keys.

-or- length 小于零。length is less than zero.

items 不是 null,且 keys 的下限与 items 的下限不匹配。items is not null, and the lower bound of keys does not match the lower bound of items.

- 或 --or- items 不是 null,并且 keys 的长度大于 items 的长度。items is not null, and the length of keys is greater than the length of items.

-or- indexlength 未在 keysArray 中指定有效范围。index and length do not specify a valid range in the keysArray.

- 或 --or- items 不为 null,且 indexlength 未在 itemsArray 中指定有效范围。items is not null, and index and length do not specify a valid range in the itemsArray.

keysArray 中的一个或多个元素不实现 IComparable<T> 泛型接口。One or more elements in the keysArray do not implement the IComparable<T> generic interface.

示例

下面的代码示例演示了Sort<TKey,TValue>(TKey[], TValue[])Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)、[]、TValue<x: system.object% 60% 602% 28% 60% 600% 5b% 5d% 2c% 60% 601% 5b% 5d% 2csystem.string% 2csystem.string% 29 > 和Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)泛型方法重载, 用于对表示键和值的数组对进行排序。The following code example demonstrates the Sort<TKey,TValue>(TKey[], TValue[]), Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), [], TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Int32%2CSystem.Int32%29>, and Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) generic method overloads, for sorting pairs of arrays that represent keys and values.

此代码示例定义了一个名为ReverseCompare的字符串的替代比较器, 该比较器实现了IComparer<string> ( C++IComparer(Of String)在 Visual Basic IComparer<String^>中的 Visual) 泛型接口。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. 比较器调用CompareTo(String)方法, 并反转比较数的顺序, 以便字符串排序为高到低而不是低到高。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:

备注

对泛型方法的调用与对它们的非泛型方法的调用没有任何不同之处, 因为C#Visual Basic、 C++和从前两个自变量的类型推断泛型类型参数的类型。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. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

using namespace System;
using namespace System::Collections::Generic;

public ref class ReverseComparer: IComparer<String^>
{
public:
    virtual int Compare(String^ x, String^ y)
    {
        // Compare y and x in reverse order.
        return y->CompareTo(x);
    }
};

void main()
{
    array<String^>^ dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

    array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes)");
    Array::Sort(dinosaurs, dinosaurSizes);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
    Array::Sort(dinosaurs, dinosaurSizes, rc);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
    Array::Sort(dinosaurs, dinosaurSizes, 3, 3);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
    Array::Sort(dinosaurs, dinosaurSizes, 3, 3, rc);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
using System;
using System.Collections.Generic;

public class ReverseComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        // Compare y and x in reverse order.
        return y.CompareTo(x);
    }
}

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

        int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes)");
        Array.Sort(dinosaurs, dinosaurSizes);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
        Array.Sort(dinosaurs, dinosaurSizes, rc);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
Imports System
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.

注解

keys中的Array每个键在中items都有相应Array的项。Each key in the keysArray has a corresponding item in the itemsArray. 当在排序过程中重定位某个键时, 中items Array的相应项同样会重新定位。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. items因此, Array会根据中keys相应键的排列顺序对进行排序。 ArrayTherefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

keys 指定范围IComparable<T>内的元素中的每个键都必须实现泛型接口,才能与其他每个键进行比较。ArrayEach 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. 如果键比项多, 则无法排序;这样做会引发ArgumentExceptionYou 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.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 On (log n) 运算, 其中nlengthFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

另请参阅

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

基于第一个 Array 中的关键字,使用指定的 Array 泛型接口,对两个 IComparer<T> 对象(一个包含关键字,另一个包含对应的项)的部分元素进行排序。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.

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

类型参数

TKey

关键字数组元素的类型。The type of the elements of the key array.

TValue

项数组元素的类型。The type of the elements of the items array.

参数

keys
TKey[]

从零开始的一维 Array,它包含要排序的关键字。The one-dimensional, zero-based Array that contains the keys to sort.

items
TValue[]

从零开始的一维 Array,其中包含与 keys 中的关键字对应的项;如果为 null,则只对 keys 进行排序。The one-dimensional, zero-based Array that contains the items that correspond to the keys in keys, or null to sort only keys.

index
Int32 Int32 Int32 Int32

排序范围的起始索引。The starting index of the range to sort.

length
Int32 Int32 Int32 Int32

排序范围内的元素数。The number of elements in the range to sort.

comparer
IComparer<TKey>

比较元素时使用的 IComparer<T> 泛型接口实现;如果为 null,则使用每个元素的 IComparable<T> 泛型接口实现。The IComparer<T> generic interface implementation to use when comparing elements, or null to use the IComparable<T> generic interface implementation of each element.

异常

index 小于 keys 的下限。index is less than the lower bound of keys.

-or- length 小于零。length is less than zero.

items 不是 null,且 keys 的下限与 items 的下限不匹配。items is not null, and the lower bound of keys does not match the lower bound of items.

-or- items 不是 null,并且 keys 的长度大于 items 的长度。items is not null, and the length of keys is greater than the length of items.

-or- indexlength 未在 keysArray 中指定有效范围。index and length do not specify a valid range in the keysArray.

-or- items 不为 null,且 indexlength 未在 itemsArray 中指定有效范围。items is not null, and index and length do not specify a valid range in the itemsArray.

-or- comparer 的实现导致排序时出现错误。The implementation of comparer caused an error during the sort. 例如,将某个项与其自身比较时,comparer 可能不返回 0。For example, comparer might not return 0 when comparing an item with itself.

comparernull,且 keysArray 中的一个或多个元素未实现 IComparable<T> 泛型接口。comparer is null, and one or more elements in the keysArray do not implement the IComparable<T> generic interface.

示例

下面的代码示例演示了Sort<TKey,TValue>(TKey[], TValue[])Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)和 [], TValue<x:% 60% 602% 28% 60% 600% 5b% 5d% 2c% 60% 601% 5b% 5d% 2csystem.string% 2csystem.string%2Csystem.string IComparer% 7B% 60% 600% 7D% 29 > 泛型方法重载, 用于对表示键和值的数组对进行排序。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 [], TValue<xref:System.Array.Sort%60%602%28%60%600%5B%5D%2C%60%601%5B%5D%2CSystem.Int32%2CSystem.Int32%2CSystem.Collections.Generic.IComparer%7B%60%600%7D%29> generic method overloads, for sorting pairs of arrays that represent keys and values.

此代码示例定义了一个名为ReverseCompare的字符串的替代比较器, 该比较器实现了IComparer<string>( C++IComparer(Of String)在 Visual Basic IComparer<String^>中的 Visual) 泛型接口。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. 比较器调用CompareTo(String)方法, 并反转比较数的顺序, 以便字符串排序为高到低而不是低到高。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:

备注

对泛型方法的调用与对它们的非泛型方法的调用没有任何不同之处, 因为C#Visual Basic、 C++和从前两个自变量的类型推断泛型类型参数的类型。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. 如果使用Ildasm (IL 拆装器)检查 Microsoft 中间语言 (MSIL), 可以看到正在调用泛型方法。If you use the Ildasm.exe (IL Disassembler) to examine the Microsoft intermediate language (MSIL), you can see that the generic methods are being called.

using namespace System;
using namespace System::Collections::Generic;

public ref class ReverseComparer: IComparer<String^>
{
public:
    virtual int Compare(String^ x, String^ y)
    {
        // Compare y and x in reverse order.
        return y->CompareTo(x);
    }
};

void main()
{
    array<String^>^ dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

    array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes)");
    Array::Sort(dinosaurs, dinosaurSizes);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    ReverseComparer^ rc = gcnew ReverseComparer();

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
    Array::Sort(dinosaurs, dinosaurSizes, rc);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
    Array::Sort(dinosaurs, dinosaurSizes, 3, 3);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }

    Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
    Array::Sort(dinosaurs, dinosaurSizes, 3, 3, rc);

    Console::WriteLine();
    for (int i = 0; i < dinosaurs->Length; i++)
    {
        Console::WriteLine("{0}: up to {1} meters long.", 
            dinosaurs[i], dinosaurSizes[i]);
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
using System;
using System.Collections.Generic;

public class ReverseComparer: IComparer<string>
{
    public int Compare(string x, string y)
    {
        // Compare y and x in reverse order.
        return y.CompareTo(x);
    }
}

public class Example
{
    public static void Main()
    {
        string[] dinosaurs = {
            "Seismosaurus", 
            "Chasmosaurus", 
            "Coelophysis", 
            "Mamenchisaurus", 
            "Caudipteryx", 
            "Cetiosaurus"  };

        int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes)");
        Array.Sort(dinosaurs, dinosaurSizes);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        ReverseComparer rc = new ReverseComparer();

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
        Array.Sort(dinosaurs, dinosaurSizes, rc);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }

        Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
        Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc);

        Console.WriteLine();
        for (int i = 0; i < dinosaurs.Length; i++)
        {
            Console.WriteLine("{0}: up to {1} meters long.", 
                dinosaurs[i], dinosaurSizes[i]);
        }
    }
}

/* This code example produces the following output:

Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.

Sort(dinosaurs, dinosaurSizes)

Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.

Sort(dinosaurs, dinosaurSizes, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.

Sort(dinosaurs, dinosaurSizes, 3, 3, rc)

Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
 */
Imports System
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.

注解

keys中的Array每个键在中items都有相应Array的项。Each key in the keysArray has a corresponding item in the itemsArray. 当在排序过程中重定位某个键时, 中items Array的相应项同样会重新定位。When a key is repositioned during the sorting, the corresponding item in the itemsArray is similarly repositioned. items因此, Array会根据中keys相应键的排列顺序对进行排序。 ArrayTherefore, the itemsArray is sorted according to the arrangement of the corresponding keys in the keysArray.

如果comparernull, 则keys 中指定范围内的元素中的每个键都必须实现泛型接口,才能与其他每个键进行比较。Array IComparable<T>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. 如果键比项多, 则无法排序;这样做会引发ArgumentExceptionYou 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.

此方法使用反省 sort (introsort) 算法, 如下所示:This method uses the introspective sort (introsort) algorithm as follows:

  • 如果分区大小少于16个, 则使用插入排序算法。If the partition size is fewer than 16 elements, it uses an insertion sort algorithm.

  • 如果分区数超过 2 * LogN, 其中N为输入数组的范围, 则使用Heapsort算法。If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm.

  • 否则, 它将使用快速排序算法。Otherwise, it uses a 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.

对于使用 Heapsort 和快速排序算法排序的数组, 在最坏的情况下, 此方法为 On (log n) 运算, 其中nlengthFor arrays that are sorted by using the Heapsort and Quicksort algorithms, in the worst case, this method is an O(n log n) operation, where n is length.

调用方说明

.NET Framework 4 及更早版本仅使用快速排序算法。The .NET Framework 4 and earlier versions used only the Quicksort algorithm. 快速排序在某些情况下标识无效的比较器, 其中排序操作IndexOutOfRangeException引发异常, 并向ArgumentException调用方引发异常。Quicksort identifies invalid comparers in some situations in which the sorting operation throws an IndexOutOfRangeException exception, and throws an ArgumentException exception to the caller. 从开始ArgumentException , 以前引发的排序操作可能不会引发异常, 因为插入排序和 heapsort 算法未检测到无效的比较器。 .NET Framework 4.5.NET Framework 4.5Starting with the .NET Framework 4.5.NET Framework 4.5, it is possible that sorting operations that previously threw ArgumentException will not throw an exception, because the insertion sort and heapsort algorithms do not detect an invalid comparer. 大多数情况下, 这适用于元素少于16个的数组。For the most part, this applies to arrays with fewer than 16 elements.

另请参阅

适用于