# Array.SortArray.SortArray.SortArray.Sort Method

## 多載

 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[]) Sort(T[]) Sort(T[]) Sort(T[]) 使用 Array 的每個元素之 IComparable 泛型介面實作，排序整個 Array 中的元素。Sorts the elements in an entire Array using the IComparable generic interface implementation of each element of the Array. Sort(T[], IComparer) Sort(T[], IComparer) Sort(T[], IComparer) Sort(T[], IComparer) 使用指定的 Array 泛型介面，排序 IComparer 中的元素。Sorts the elements in an Array using the specified IComparer generic interface. Sort(T[], Comparison) Sort(T[], Comparison) Sort(T[], Comparison) Sort(T[], Comparison) 使用指定的 Array，排序 Comparison 中的元素。Sorts the elements in an Array using the specified Comparison. Sort(T[], Int32, Int32) Sort(T[], Int32, Int32) Sort(T[], Int32, Int32) Sort(T[], Int32, Int32) 使用 Array 的每個元素之 IComparable 泛型介面實作，排序 Array 中某個元素範圍中的元素。Sorts the elements in a range of elements in an Array using the IComparable generic interface implementation of each element of the Array. Sort(T[], Int32, Int32, IComparer) Sort(T[], Int32, Int32, IComparer) Sort(T[], Int32, Int32, IComparer) Sort(T[], Int32, Int32, IComparer) 使用指定的 Array 泛型介面，對 IComparer 中的某個元素範圍內的元素進行排序。Sorts the elements in a range of elements in an Array using the specified IComparer generic interface. Sort(TKey[], TValue[]) Sort(TKey[], TValue[]) Sort(TKey[], TValue[]) Sort(TKey[], TValue[]) 使用每個索引鍵的 Array 泛型介面實作，根據第一個 Array 中的索引鍵，排序一對 IComparable 物件 (一個物件包含索引鍵，另一個物件包含對應的項目)。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 generic interface implementation of each key. Sort(TKey[], TValue[], IComparer) Sort(TKey[], TValue[], IComparer) Sort(TKey[], TValue[], IComparer) Sort(TKey[], TValue[], IComparer) 使用指定的 Array 泛型介面，根據第一個 Array 中的索引鍵，排序一對 IComparer 物件 (一個物件包含索引鍵，另一個物件包含對應的項目)。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 generic interface. Sort(TKey[], TValue[], Int32, Int32) Sort(TKey[], TValue[], Int32, Int32) Sort(TKey[], TValue[], Int32, Int32) Sort(TKey[], TValue[], Int32, Int32) 使用每個索引鍵的 Array 泛型介面實作，根據第一個 Array 中的索引鍵，排序一對 IComparable 物件中某個範圍的元素 (一個物件包含索引鍵，另一個物件包含對應的項目)。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 generic interface implementation of each key. Sort(TKey[], TValue[], Int32, Int32, IComparer) Sort(TKey[], TValue[], Int32, Int32, IComparer) Sort(TKey[], TValue[], Int32, Int32, IComparer) Sort(TKey[], TValue[], Int32, Int32, IComparer) 使用指定的 Array 泛型介面，根據第一個 Array 中的索引鍵，排序一對 IComparer 物件中某範圍的元素 (一個物件包含索引鍵，另一個物件包含對應的項目)。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 generic interface.

## Sort(Array, Int32, Int32, IComparer)Sort(Array, Int32, Int32, IComparer)Sort(Array, Int32, Int32, 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

index
Int32 Int32 Int32 Int32

length
Int32 Int32 Int32 Int32

comparer
IComparer IComparer IComparer IComparer

-或--or- `null` 表示會使用每個項目的 IComparable 實作。`null` to use the IComparable implementation of each element.

#### 例外狀況

`array``null``array` is `null`.

`array` 是多維的。`array` is multidimensional.

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

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

`index``length` 未指定 `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.

`comparer``null`，而且 `array` 中的一個或多個元素沒有實作 IComparable 介面。`comparer` is `null`, and one or more elements in `array` do not implement the IComparable interface.

### 範例

``````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
``````

### 備註

.NET Framework 包含下表IComparer所列的預先定義的實作為。The .NET Framework includes predefined IComparer implementations listed in the following table.

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.

• 如果分割區大小少於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.

### 給呼叫者的注意事項

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

``````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

items
Array Array Array Array

-或--or- `null` 表示只排序 `keys`Array`null` to sort only the `keys`Array.

index
Int32 Int32 Int32 Int32

length
Int32 Int32 Int32 Int32

comparer
IComparer IComparer IComparer IComparer

-或--or- `null` 表示會使用每個項目的 IComparable 實作。`null` to use the IComparable implementation of each element.

#### 例外狀況

`keys``null``keys` is `null`.

`keys`Array 是多維的。The `keys`Array is multidimensional.

-或--or- `items`Array 是多維的。The `items`Array 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- `index``length` 未指定 `keys`Array 中的有效範圍。`index` and `length` do not specify a valid range in the `keys`Array.

-或--or- `items` 不是 `null`，且 `index``length` 未指定 `items`Array 中的有效範圍。`items` is not `null`, and `index` and `length` do not specify a valid range in the `items`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.

`comparer``null`，而且 `keys`Array 中的一或多個元素不會實作 IComparable 介面。`comparer` is `null`, and one or more elements in the `keys`Array do not implement the IComparable interface.

### 範例

``````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.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 `keys`Array has a corresponding item in the `items`Array. 當索引鍵在排序期間重新置放時，中`items` Array對應的專案也會重新置放。When a key is repositioned during the sorting, the corresponding item in the `items`Array is similarly repositioned. `items`因此， Array會根據中`keys`對應索引鍵的排列順序排序。 ArrayTherefore, the `items`Array is sorted according to the arrangement of the corresponding keys in the `keys`Array.

.NET Framework 包含下表IComparer所列的預先定義的實作為。The .NET Framework includes predefined IComparer implementations listed in the following table.

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.

• 如果分割區大小少於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.

### 給呼叫者的注意事項

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

``````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

index
Int32 Int32 Int32 Int32

length
Int32 Int32 Int32 Int32

#### 例外狀況

`array``null``array` is `null`.

`array` 是多維的。`array` is multidimensional.

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

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

`index``length` 未指定 `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.

### 範例

``````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
``````

### 備註

• 如果分割區大小少於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.

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

``````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

items
Array Array Array Array

-或--or- `null` 表示只排序 `keys`Array`null` to sort only the `keys`Array.

index
Int32 Int32 Int32 Int32

length
Int32 Int32 Int32 Int32

#### 例外狀況

`keys``null``keys` is `null`.

`keys`Array 是多維的。The `keys`Array is multidimensional.

-或--or- `items`Array 是多維的。The `items`Array 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- `index``length` 未指定 `keys`Array 中的有效範圍。`index` and `length` do not specify a valid range in the `keys`Array.

-或--or- `items` 不是 `null`，且 `index``length` 未指定 `items`Array 中的有效範圍。`items` is not `null`, and `index` and `length` do not specify a valid range in the `items`Array.

`keys`Array 中的一或多個元素不會實作 IComparable 介面。One or more elements in the `keys`Array do not implement the IComparable interface.

### 範例

``````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.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 `keys`Array has a corresponding item in the `items`Array. 當索引鍵在排序期間重新置放時，中`items` Array對應的專案也會重新置放。When a key is repositioned during the sorting, the corresponding item in the `items`Array is similarly repositioned. `items`因此， Array會根據中`keys`對應索引鍵的排列順序排序。 ArrayTherefore, the `items`Array is sorted according to the arrangement of the corresponding keys in the `keys`Array.

• 如果分割區大小少於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.

## Sort(Array, IComparer)Sort(Array, IComparer)Sort(Array, 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

comparer
IComparer IComparer IComparer IComparer

-或--or- `null` 表示會使用每個項目的 IComparable 實作。`null` to use the IComparable implementation of each element.

#### 例外狀況

`array``null``array` is `null`.

`array` 是多維的。`array` is multidimensional.

`comparer``null`，而且 `array` 中的一個或多個元素沒有實作 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.

### 範例

``````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
``````

### 備註

• 如果分割區大小少於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.

.NET Framework 包含下表IComparer所列的預先定義的實作為。The .NET Framework includes predefined IComparer implementations listed in the following table.

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.

### 給呼叫者的注意事項

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

``````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

items
Array Array Array Array

-或--or- `null` 表示只排序 `keys`Array`null` to sort only the `keys`Array.

comparer
IComparer IComparer IComparer IComparer

-或--or- `null` 表示會使用每個項目的 IComparable 實作。`null` to use the IComparable implementation of each element.

#### 例外狀況

`keys``null``keys` is `null`.

`keys`Array 是多維的。The `keys`Array is multidimensional.

-或--or- `items`Array 是多維的。The `items`Array 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.

`comparer``null`，而且 `keys`Array 中的一或多個元素不會實作 IComparable 介面。`comparer` is `null`, and one or more elements in the `keys`Array do not implement the IComparable interface.

### 範例

``````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.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 `keys`Array has a corresponding item in the `items`Array. 當索引鍵在排序期間重新置放時，中`items` Array對應的專案也會重新置放。When a key is repositioned during the sorting, the corresponding item in the `items`Array is similarly repositioned. `items`因此， Array會根據中`keys`對應索引鍵的排列順序排序。 ArrayTherefore, the `items`Array is sorted according to the arrangement of the corresponding keys in the `keys`Array.

.NET Framework 包含下表IComparer所列的預先定義的實作為。The .NET Framework includes predefined IComparer implementations listed in the following table.

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.

• 如果分割區大小少於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.

### 給呼叫者的注意事項

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

``````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

items
Array Array Array Array

-或--or- `null` 表示只排序 `keys`Array`null` to sort only the `keys`Array.

#### 例外狀況

`keys``null``keys` is `null`.

`keys`Array 是多維的。The `keys`Array is multidimensional.

-或--or- `items`Array 是多維的。The `items`Array is multidimensional.

`items` 不是 `null`，而且 `keys` 的長度大於 `items` 的長度。`items` is not `null`, and the length of `keys` is greater than the length of `items`.

`keys`Array 中的一或多個元素不會實作 IComparable 介面。One or more elements in the `keys`Array do not implement the IComparable interface.

### 範例

``````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.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 `keys`Array has a corresponding item in the `items`Array. 當索引鍵在排序期間重新置放時，中`items` Array對應的專案也會重新置放。When a key is repositioned during the sorting, the corresponding item in the `items`Array is similarly repositioned. `items`因此， Array會根據中`keys`對應索引鍵的排列順序排序。 ArrayTherefore, the `items`Array is sorted according to the arrangement of the corresponding keys in the `keys`Array.

• 如果分割區大小少於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.

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

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

#### 參數

array
Array Array Array Array

#### 例外狀況

`array``null``array` is `null`.

`array` 是多維的。`array` is multidimensional.

`array` 中的一個或多個元素沒有實作 IComparable 介面。One or more elements in `array` do not implement the IComparable interface.

### 範例

``````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`.

• 如果分割區大小少於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.

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

``````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

array
T[]

#### 例外狀況

`array``null``array` is `null`.

`array` 中的一個或多個元素沒有實作 IComparable<T> 泛型介面。One or more elements in `array` do not implement the IComparable<T> generic interface.

### 範例

Sort C#和泛型BinarySearch方法的呼叫不會與其非泛型對應專案的呼叫看起來不同，因為 Visual Basic、和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.

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

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

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;

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

BinarySearch for 'Tyrannosaurus':
Found at index 5.
*/
``````
``````Imports System.Collections.Generic

Public Class Example

Public Shared Sub Main()

Dim dinosaurs() As String = { _
"Pachycephalosaurus", _
"Amargasaurus", _
"Tyrannosaurus", _
"Mamenchisaurus", _
"Deinonychus", _
"Edmontosaurus"  }

Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next

Console.WriteLine(vbLf & "Sort")
Array.Sort(dinosaurs)

Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next

Console.WriteLine(vbLf & _
"BinarySearch for 'Coelophysis':")
Dim index As Integer = _
Array.BinarySearch(dinosaurs, "Coelophysis")
ShowWhere(dinosaurs, index)

Console.WriteLine(vbLf & _
"BinarySearch for 'Tyrannosaurus':")
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus")
ShowWhere(dinosaurs, index)

End Sub

Private Shared Sub ShowWhere(Of T) _
(ByVal array() As T, ByVal index As Integer)

If index < 0 Then
' If the index is negative, it represents the bitwise
' complement of the next larger element in the array.
'
index = index Xor -1

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':
'
'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`.

• 如果分割區大小少於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.

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

``````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

#### 參數

array
T[]

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

#### 例外狀況

`array``null``array` is `null`.

`comparer``null`，而且 `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>) C#和泛型BinarySearch<T>(T[], T, IComparer<T>)方法的呼叫不會與其非泛型對應專案的呼叫看起來不同，因為 Visual Basic、和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);
}
};

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;

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

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;

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

BinarySearch for 'Tyrannosaurus':
Found at index 0.
*/
``````
``````Imports System.Collections.Generic

Public Class ReverseComparer
Implements IComparer(Of String)

Public Function Compare(ByVal x As String, _
ByVal y As String) As Integer _
Implements IComparer(Of String).Compare

' Compare y and x in reverse order.
Return y.CompareTo(x)

End Function
End Class

Public Class Example

Public Shared Sub Main()

Dim dinosaurs() As String = { _
"Pachycephalosaurus", _
"Amargasaurus", _
"Tyrannosaurus", _
"Mamenchisaurus", _
"Deinonychus", _
"Edmontosaurus"  }

Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next

Dim rc As New ReverseComparer()

Console.WriteLine(vbLf & "Sort")
Array.Sort(dinosaurs, rc)

Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next

Console.WriteLine(vbLf & _
"BinarySearch for 'Coelophysis':")
Dim index As Integer = _
Array.BinarySearch(dinosaurs, "Coelophysis", rc)
ShowWhere(dinosaurs, index)

Console.WriteLine(vbLf & _
"BinarySearch for 'Tyrannosaurus':")
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
ShowWhere(dinosaurs, index)

End Sub

Private Shared Sub ShowWhere(Of T) _
(ByVal array() As T, ByVal index As Integer)

If index < 0 Then
' If the index is negative, it represents the bitwise
' complement of the next larger element in the array.
'
index = index Xor -1

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':
'
'BinarySearch for 'Tyrannosaurus':
'Found at index 0.
``````

### 備註

• 如果分割區大小少於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.

### 給呼叫者的注意事項

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

``````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

#### 參數

array
T[]

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

#### 例外狀況

`array``null``array` is `null`.

-或--or- `comparison``null``comparison` 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.

### 範例

``````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.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:")
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"
``````

### 備註

• 如果分割區大小少於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.

### 給呼叫者的注意事項

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

``````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

#### 參數

array
T[]

index
Int32 Int32 Int32 Int32

length
Int32 Int32 Int32 Int32

#### 例外狀況

`array``null``array` is `null`.

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

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

`index``length` 未指定 `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[], IComparer<T>) C#和泛型BinarySearch<T>(T[], T, IComparer<T>)方法的呼叫不會與其非泛型對應專案的呼叫看起來不同，因為 Visual Basic、和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.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
``````

### 備註

• 如果分割區大小少於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.

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

``````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

#### 參數

array
T[]

index
Int32 Int32 Int32 Int32

length
Int32 Int32 Int32 Int32

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

#### 例外狀況

`array``null``array` is `null`.

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

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

`index``length` 未指定 `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.

`comparer``null`，而且 `array` 中的一個或多個元素沒有實作 IComparable<T> 泛型介面。`comparer` is `null`, and one or more elements in `array` do not implement the IComparable<T> generic interface.

### 範例

Sort<T>(T[], IComparer<T>) C#和泛型BinarySearch<T>(T[], T, IComparer<T>)方法的呼叫不會與其非泛型對應專案的呼叫看起來不同，因為 Visual Basic、和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.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
``````

### 備註

• 如果分割區大小少於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.

### 給呼叫者的注意事項

.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[])

``````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

TValue

keys
TKey[]

items
TValue[]

#### 例外狀況

`keys``null``keys` is `null`.

`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`.

`keys`Array 中的一個或多個元素不會實作 IComparable<T> 泛型介面。One or more elements in the `keys`Array do not implement the IComparable<T> generic interface.

### 範例

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.

``````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.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 `keys`Array has a corresponding item in the `items`Array. 當索引鍵在排序期間重新置放時，中`items` Array對應的專案也會重新置放。When a key is repositioned during the sorting, the corresponding item in the `items`Array is similarly repositioned. `items`因此， Array會根據中`keys`對應索引鍵的排列順序排序。 ArrayTherefore, the `items`Array is sorted according to the arrangement of the corresponding keys in the `keys`Array.

• 如果分割區大小少於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.

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

``````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

TValue

keys
TKey[]

items
TValue[]

comparer
IComparer<TKey>

#### 例外狀況

`keys``null``keys` is `null`.

`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.

`comparer``null`，而且 `keys`Array 中的一或多個元素未實作 IComparable<T> 泛型介面。`comparer` is `null`, and one or more elements in the `keys`Array do not implement the IComparable<T> generic interface.

### 範例

``````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.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 `keys`Array has a corresponding item in the `items`Array. 當索引鍵在排序期間重新置放時，中`items` Array對應的專案也會重新置放。When a key is repositioned during the sorting, the corresponding item in the `items`Array is similarly repositioned. `items`因此， Array會根據中`keys`對應索引鍵的排列順序排序。 ArrayTherefore, the `items`Array is sorted according to the arrangement of the corresponding keys in the `keys`Array.

• 如果分割區大小少於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.

### 給呼叫者的注意事項

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

``````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

TValue

#### 參數

keys
TKey[]

items
TValue[]

index
Int32 Int32 Int32 Int32

length
Int32 Int32 Int32 Int32

#### 例外狀況

`keys``null``keys` is `null`.

`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- `index``length` 未指定 `keys`Array 中的有效範圍。`index` and `length` do not specify a valid range in the `keys`Array.

-或--or- `items` 不是 `null`，且 `index``length` 未指定 `items`Array 中的有效範圍。`items` is not `null`, and `index` and `length` do not specify a valid range in the `items`Array.

`keys`Array 中的一個或多個元素不會實作 IComparable<T> 泛型介面。One or more elements in the `keys`Array do not implement the IComparable<T> generic interface.

### 範例

``````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.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 `keys`Array has a corresponding item in the `items`Array. 當索引鍵在排序期間重新置放時，中`items` Array對應的專案也會重新置放。When a key is repositioned during the sorting, the corresponding item in the `items`Array is similarly repositioned. `items`因此， Array會根據中`keys`對應索引鍵的排列順序排序。 ArrayTherefore, the `items`Array is sorted according to the arrangement of the corresponding keys in the `keys`Array.

• 如果分割區大小少於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.

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

``````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

TValue

#### 參數

keys
TKey[]

items
TValue[]

index
Int32 Int32 Int32 Int32

length
Int32 Int32 Int32 Int32

comparer
IComparer<TKey>

#### 例外狀況

`keys``null``keys` is `null`.

`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- `index``length` 未指定 `keys`Array 中的有效範圍。`index` and `length` do not specify a valid range in the `keys`Array.

-或--or- `items` 不是 `null`，且 `index``length` 未指定 `items`Array 中的有效範圍。`items` is not `null`, and `index` and `length` do not specify a valid range in the `items`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.

`comparer``null`，而且 `keys`Array 中的一或多個元素未實作 IComparable<T> 泛型介面。`comparer` is `null`, and one or more elements in the `keys`Array do not implement the IComparable<T> generic interface.

### 範例

``````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.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 `keys`Array has a corresponding item in the `items`Array. 當索引鍵在排序期間重新置放時，中`items` Array對應的專案也會重新置放。When a key is repositioned during the sorting, the corresponding item in the `items`Array is similarly repositioned. `items`因此， Array會根據中`keys`對應索引鍵的排列順序排序。 ArrayTherefore, the `items`Array is sorted according to the arrangement of the corresponding keys in the `keys`Array.

• 如果分割區大小少於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.

### 給呼叫者的注意事項

.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.