Array.Sort 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
对一维数组中的元素进行排序。
重载
Sort(Array, Array, Int32, Int32, IComparer)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
public:
static void Sort(Array ^ keys, Array ^ items, int index, int length, System::Collections::IComparer ^ comparer);
public static void Sort (Array keys, Array items, int index, int length, System.Collections.IComparer comparer);
public static void Sort (Array keys, Array? items, int index, int length, System.Collections.IComparer? comparer);
static member Sort : Array * Array * int * int * System.Collections.IComparer -> unit
Public Shared Sub Sort (keys As Array, items As Array, index As Integer, length As Integer, comparer As IComparer)
参数
- index
- Int32
要排序的范围的起始索引。
- length
- Int32
要排序的范围中的元素数。
例外
keys
null
。
items
不 null
,keys
的下限与 items
的下限不匹配。
-或-
items
不 null
,keys
的长度大于 items
长度。
-或-
index
和 length
未在 keys
Array中指定有效范围。
-或-
items
不 null
,index
和 length
未在 items
Array中指定有效范围。
-或-
comparer
的实现在排序过程中导致错误。 例如,将项与自身进行比较时,comparer
可能不会返回 0。
comparer
null
,keys
Array 中的一个或多个元素不实现 IComparable 接口。
示例
下面的代码示例演示如何对两个关联的数组进行排序,其中第一个数组包含键,第二个数组包含值。 排序是使用默认比较器和一个反转排序顺序的自定义比较器完成的。 请注意,结果可能因当前 CultureInfo而异。
using namespace System;
using namespace System::Collections;
public ref class myReverserClass: public IComparer
{
private:
// Calls CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
}
};
void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
for ( int i = 0; i < myKeys->Length; i++ )
{
Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
}
Console::WriteLine();
}
int main()
{
// Creates and initializes a new Array and a new custom comparer.
array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
IComparer^ myComparer = gcnew myReverserClass;
// Displays the values of the Array.
Console::WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array::Sort( myKeys, myValues, 1, 3 );
Console::WriteLine( "After sorting a section of the Array using the default comparer:" );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, 1, 3, myComparer );
Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array::Sort( myKeys, myValues );
Console::WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, myComparer );
Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
using System;
using System.Collections;
public class SamplesArray {
public class myReverserClass : IComparer {
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare( Object x, Object y ) {
return( (new CaseInsensitiveComparer()).Compare( y, x ) );
}
}
public static void Main() {
// Creates and initializes a new Array and a new custom comparer.
String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
IComparer myComparer = new myReverserClass();
// Displays the values of the Array.
Console.WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array.Sort( myKeys, myValues, 1, 3 );
Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, 1, 3, myComparer );
Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array.Sort( myKeys, myValues );
Console.WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, myComparer );
Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
public static void PrintKeysAndValues( String[] myKeys, String[] myValues ) {
for ( int i = 0; i < myKeys.Length; i++ ) {
Console.WriteLine( " {0,-10}: {1}", myKeys[i], myValues[i] );
}
Console.WriteLine();
}
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
open System
open System.Collections
type MyReverserClass() =
interface IComparer with
member _.Compare(x, y) =
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let printKeysAndValues (myKeys: string []) (myValues: string []) =
for i = 0 to myKeys.Length - 1 do
printfn $" {myKeys[i],-10}: {myValues[i]}"
printfn ""
// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()
// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// This code produces the following output.
// The Array initially contains the following values:
// red : strawberries
// GREEN : PEARS
// YELLOW : LIMES
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the default comparer:
// red : strawberries
// BLUE : BERRIES
// GREEN : PEARS
// YELLOW : LIMES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the reverse case-insensitive comparer:
// red : strawberries
// YELLOW : LIMES
// GREEN : PEARS
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting the entire Array using the default comparer:
// black : olives
// BLUE : BERRIES
// GREEN : PEARS
// orange : cantaloupe
// purple : grapes
// red : strawberries
// YELLOW : LIMES
//
// After sorting the entire Array using the reverse case-insensitive comparer:
// YELLOW : LIMES
// red : strawberries
// purple : grapes
// orange : cantaloupe
// GREEN : PEARS
// BLUE : BERRIES
// black : olives
Imports System.Collections
Public Class SamplesArray
Public Class myReverserClass
Implements IComparer
' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As [Object], y As [Object]) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function 'IComparer.Compare
End Class
Public Shared Sub Main()
' Creates and initializes a new Array and a new custom comparer.
Dim myKeys As [String]() = {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
Dim myValues As [String]() = {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
Dim myComparer = New myReverserClass()
' Displays the values of the Array.
Console.WriteLine("The Array initially contains the following values:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
Console.WriteLine("After sorting a section of the Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
Console.WriteLine("After sorting the entire Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
End Sub
Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])
Dim i As Integer
For i = 0 To myKeys.Length - 1
Console.WriteLine(" {0,-10}: {1}", myKeys(i), myValues(i))
Next i
Console.WriteLine()
End Sub
End Class
'This code produces the following output.
'
'The Array initially contains the following values:
' red : strawberries
' GREEN : PEARS
' YELLOW : LIMES
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the default comparer:
' red : strawberries
' BLUE : BERRIES
' GREEN : PEARS
' YELLOW : LIMES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
' red : strawberries
' YELLOW : LIMES
' GREEN : PEARS
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting the entire Array using the default comparer:
' black : olives
' BLUE : BERRIES
' GREEN : PEARS
' orange : cantaloupe
' purple : grapes
' red : strawberries
' YELLOW : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
' YELLOW : LIMES
' red : strawberries
' purple : grapes
' orange : cantaloupe
' GREEN : PEARS
' BLUE : BERRIES
' black : olives
注解
keys
Array 中的每个键在 items
Array中都有相应的项。 当键在排序期间重新定位时,items
Array 中的相应项将同样重新定位。 因此,items
Array 按照 keys
Array中相应键的排列方式进行排序。
如果 comparer
null
,则 keys
Array 中指定范围内的元素中的每个键都必须实现 IComparable 接口才能与其他每个键进行比较。
如果项数多于键,则可以进行排序,但没有相应键的项将不会进行排序。 如果键数多于项,则无法排序;执行此操作会引发 ArgumentException。
如果排序未成功完成,则结果未定义。
.NET 包括下表中列出的预定义 IComparer 实现。
实现 | 描述 |
---|---|
System.Collections.CaseInsensitiveComparer | 比较任何两个对象,但对字符串执行不区分大小写的比较。 |
Comparer.Default | 使用当前区域性的排序约定比较任何两个对象。 |
Comparer.DefaultInvariant | 使用固定区域性的排序约定比较任意两个对象。 |
Comparer<T>.Default | 使用类型的默认排序顺序比较类型 T 的两个对象。 |
还可以通过向 comparer
参数提供自己的 IComparer 实现实例来支持自定义比较。 此示例通过定义一个自定义 IComparer 实现来反转默认排序顺序并执行不区分大小写的字符串比较来执行此操作。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
length
。
调用方说明
.NET Framework 4 和早期版本仅使用 Quicksort 算法。 在排序操作引发 IndexOutOfRangeException 异常,并向调用方引发 ArgumentException 异常的情况下,Quicksort 标识无效比较器。 从 .NET Framework 4.5 开始,以前引发 ArgumentException 的排序操作可能不会引发异常,因为插入排序和堆算法不会检测到无效比较器。 在大多数情况下,这适用于小于或等于 16 个元素的数组。
另请参阅
- IComparer
- IComparable
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort(Array, Int32, Int32, IComparer)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
public:
static void Sort(Array ^ array, int index, int length, System::Collections::IComparer ^ comparer);
public static void Sort (Array array, int index, int length, System.Collections.IComparer comparer);
public static void Sort (Array array, int index, int length, System.Collections.IComparer? comparer);
static member Sort : Array * int * int * System.Collections.IComparer -> unit
Public Shared Sub Sort (array As Array, index As Integer, length As Integer, comparer As IComparer)
参数
- index
- Int32
要排序的范围的起始索引。
- length
- Int32
要排序的范围中的元素数。
例外
array
null
。
array
是多维的。
index
和 length
未在 array
中指定有效范围。
-或-
comparer
的实现在排序过程中导致错误。 例如,将项与自身进行比较时,comparer
可能不会返回 0。
comparer
null
,array
中的一个或多个元素不实现 IComparable 接口。
示例
下面的代码示例演示如何使用默认比较器和反转排序顺序的自定义比较器对 Array 中的值进行排序。 请注意,结果可能因当前 CultureInfo而异。
using namespace System;
using namespace System::Collections;
public ref class ReverseComparer : IComparer
{
public:
// Call CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
}
};
void DisplayValues(array<String^>^ arr)
{
for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
Console::WriteLine( " [{0}] : {1}", i, arr[ i ] );
Console::WriteLine();
}
int main()
{
// Create and initialize a new array. and a new custom comparer.
array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
"over","the","lazy","dog" };
// Instantiate the reverse comparer.
IComparer^ revComparer = gcnew ReverseComparer();
// Display the values of the Array.
Console::WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array::Sort(words, 1, 3);
Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array::Sort(words, 1, 3, revComparer);
Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array::Sort(words);
Console::WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array::Sort(words, revComparer);
Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
/*
This code produces the following output.
The Array initially contains the following values:
[0] : The
[1] : QUICK
[2] : BROWN
[3] : FOX
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the default comparer:
[0] : The
[1] : BROWN
[2] : FOX
[3] : QUICK
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the reverse case-insensitive comparer:
[0] : The
[1] : QUICK
[2] : FOX
[3] : BROWN
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting the entire Array using the default comparer:
[0] : BROWN
[1] : dog
[2] : FOX
[3] : jumps
[4] : lazy
[5] : over
[6] : QUICK
[7] : the
[8] : The
After sorting the entire Array using the reverse case-insensitive comparer:
[0] : the
[1] : The
[2] : QUICK
[3] : over
[4] : lazy
[5] : jumps
[6] : FOX
[7] : dog
[8] : BROWN
*/
using System;
using System.Collections;
public class ReverseComparer : IComparer
{
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
public int Compare(Object x, Object y)
{
return (new CaseInsensitiveComparer()).Compare(y, x );
}
}
public class Example
{
public static void Main()
{
// Create and initialize a new array.
String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" };
// Instantiate the reverse comparer.
IComparer revComparer = new ReverseComparer();
// Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3);
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer);
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array.Sort(words);
Console.WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer);
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
public static void DisplayValues(String[] arr)
{
for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
i++ ) {
Console.WriteLine( " [{0}] : {1}", i, arr[i] );
}
Console.WriteLine();
}
}
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
open System
open System.Collections
type ReverseComparer() =
interface IComparer with
member _.Compare(x, y) =
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let displayValues (arr: string []) =
for i = 0 to arr.Length - 1 do
printfn $" [{i}] : {arr[i]}"
printfn ""
// Create and initialize a new array.
let words =
[| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
"over"; "the"; "lazy"; "dog" |]
// Instantiate the reverse comparer.
let revComparer = ReverseComparer()
// Display the values of the array.
printfn "The original order of elements in the array:"
displayValues words
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
printfn "After sorting elements 1-3 by using the default comparer:"
displayValues words
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
printfn "After sorting elements 1-3 by using the reverse case-insensitive comparer:"
displayValues words
// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
Imports System.Collections
Public Class ReverseComparer : Implements IComparer
' Call CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As Object, y As Object) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function
End Class
Public Module Example
Public Sub Main()
' Create and initialize a new array.
Dim words() As String = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" }
' Instantiate a new custom comparer.
Dim revComparer As New ReverseComparer()
' Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" )
DisplayValues(words)
' Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:")
DisplayValues(words)
' Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:")
DisplayValues(words)
' Sort the entire array using the default comparer.
Array.Sort(words)
Console.WriteLine( "After sorting the entire array by using the default comparer:")
DisplayValues(words)
' Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:")
DisplayValues(words)
End Sub
Public Sub DisplayValues(arr() As String)
For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
Console.WriteLine(" [{0}] : {1}", i, arr(i))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' The original order of elements in the array:
' [0] : The
' [1] : QUICK
' [2] : BROWN
' [3] : FOX
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the default comparer:
' [0] : The
' [1] : BROWN
' [2] : FOX
' [3] : QUICK
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the reverse case-insensitive comparer:
' [0] : The
' [1] : QUICK
' [2] : FOX
' [3] : BROWN
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting the entire array by using the default comparer:
' [0] : BROWN
' [1] : dog
' [2] : FOX
' [3] : jumps
' [4] : lazy
' [5] : over
' [6] : QUICK
' [7] : the
' [8] : The
'
' After sorting the entire array using the reverse case-insensitive comparer:
' [0] : the
' [1] : The
' [2] : QUICK
' [3] : over
' [4] : lazy
' [5] : jumps
' [6] : FOX
' [7] : dog
' [8] : BROWN
注解
如果 comparer
null
,array
中指定元素范围内的每个元素都必须实现 IComparable 接口才能与 array
中所有其他元素进行比较。
如果排序未成功完成,则结果未定义。
.NET 包括下表中列出的预定义 IComparer 实现。
实现 | 描述 |
---|---|
System.Collections.CaseInsensitiveComparer | 比较任何两个对象,但对字符串执行不区分大小写的比较。 |
Comparer.Default | 使用当前区域性的排序约定比较任何两个对象。 |
Comparer.DefaultInvariant | 使用固定区域性的排序约定比较任意两个对象。 |
Comparer<T>.Default | 使用类型的默认排序顺序比较类型 T 的两个对象。 |
还可以通过向 comparer
参数提供自己的 IComparer 实现实例来支持自定义比较。 该示例通过定义一个 ReverseComparer
类来反转类型实例的默认排序顺序,并执行不区分大小写的字符串比较。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
length
。
调用方说明
.NET Framework 4 和早期版本仅使用 Quicksort 算法。 在排序操作引发 IndexOutOfRangeException 异常,并向调用方引发 ArgumentException 异常的情况下,Quicksort 标识无效比较器。 从 .NET Framework 4.5 开始,以前引发 ArgumentException 的排序操作可能不会引发异常,因为插入排序和堆算法不会检测到无效比较器。 在大多数情况下,这适用于小于或等于 16 个元素的数组。
另请参阅
- IComparer
- IComparable
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort(Array, Array, Int32, Int32)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
根据 Array 每个键的 IComparable 实现,对一个一维 Array 对象(一个包含键,另一个对象包含相应的项)中的元素范围进行排序。
public:
static void Sort(Array ^ keys, Array ^ items, int index, int length);
public static void Sort (Array keys, Array items, int index, int length);
public static void Sort (Array keys, Array? items, int index, int length);
static member Sort : Array * Array * int * int -> unit
Public Shared Sub Sort (keys As Array, items As Array, index As Integer, length As Integer)
参数
- index
- Int32
要排序的范围的起始索引。
- length
- Int32
要排序的范围中的元素数。
例外
keys
null
。
items
不 null
,keys
的长度大于 items
长度。
-或-
index
和 length
未在 keys
Array中指定有效范围。
-或-
items
不 null
,index
和 length
未在 items
Array中指定有效范围。
keys
Array 中的一个或多个元素不实现 IComparable 接口。
示例
下面的代码示例演示如何对两个关联的数组进行排序,其中第一个数组包含键,第二个数组包含值。 排序是使用默认比较器和一个反转排序顺序的自定义比较器完成的。 请注意,结果可能因当前 CultureInfo而异。
using namespace System;
using namespace System::Collections;
public ref class myReverserClass: public IComparer
{
private:
// Calls CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
}
};
void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
for ( int i = 0; i < myKeys->Length; i++ )
{
Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
}
Console::WriteLine();
}
int main()
{
// Creates and initializes a new Array and a new custom comparer.
array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
IComparer^ myComparer = gcnew myReverserClass;
// Displays the values of the Array.
Console::WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array::Sort( myKeys, myValues, 1, 3 );
Console::WriteLine( "After sorting a section of the Array using the default comparer:" );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, 1, 3, myComparer );
Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array::Sort( myKeys, myValues );
Console::WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, myComparer );
Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
using System;
using System.Collections;
public class SamplesArray {
public class myReverserClass : IComparer {
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare( Object x, Object y ) {
return( (new CaseInsensitiveComparer()).Compare( y, x ) );
}
}
public static void Main() {
// Creates and initializes a new Array and a new custom comparer.
String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
IComparer myComparer = new myReverserClass();
// Displays the values of the Array.
Console.WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array.Sort( myKeys, myValues, 1, 3 );
Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, 1, 3, myComparer );
Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array.Sort( myKeys, myValues );
Console.WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, myComparer );
Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
public static void PrintKeysAndValues( String[] myKeys, String[] myValues ) {
for ( int i = 0; i < myKeys.Length; i++ ) {
Console.WriteLine( " {0,-10}: {1}", myKeys[i], myValues[i] );
}
Console.WriteLine();
}
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
open System
open System.Collections
type MyReverserClass() =
interface IComparer with
member _.Compare(x, y) =
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let printKeysAndValues (myKeys: string []) (myValues: string []) =
for i = 0 to myKeys.Length - 1 do
printfn $" {myKeys[i],-10}: {myValues[i]}"
printfn ""
// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()
// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// This code produces the following output.
// The Array initially contains the following values:
// red : strawberries
// GREEN : PEARS
// YELLOW : LIMES
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the default comparer:
// red : strawberries
// BLUE : BERRIES
// GREEN : PEARS
// YELLOW : LIMES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the reverse case-insensitive comparer:
// red : strawberries
// YELLOW : LIMES
// GREEN : PEARS
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting the entire Array using the default comparer:
// black : olives
// BLUE : BERRIES
// GREEN : PEARS
// orange : cantaloupe
// purple : grapes
// red : strawberries
// YELLOW : LIMES
//
// After sorting the entire Array using the reverse case-insensitive comparer:
// YELLOW : LIMES
// red : strawberries
// purple : grapes
// orange : cantaloupe
// GREEN : PEARS
// BLUE : BERRIES
// black : olives
Imports System.Collections
Public Class SamplesArray
Public Class myReverserClass
Implements IComparer
' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As [Object], y As [Object]) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function 'IComparer.Compare
End Class
Public Shared Sub Main()
' Creates and initializes a new Array and a new custom comparer.
Dim myKeys As [String]() = {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
Dim myValues As [String]() = {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
Dim myComparer = New myReverserClass()
' Displays the values of the Array.
Console.WriteLine("The Array initially contains the following values:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
Console.WriteLine("After sorting a section of the Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
Console.WriteLine("After sorting the entire Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
End Sub
Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])
Dim i As Integer
For i = 0 To myKeys.Length - 1
Console.WriteLine(" {0,-10}: {1}", myKeys(i), myValues(i))
Next i
Console.WriteLine()
End Sub
End Class
'This code produces the following output.
'
'The Array initially contains the following values:
' red : strawberries
' GREEN : PEARS
' YELLOW : LIMES
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the default comparer:
' red : strawberries
' BLUE : BERRIES
' GREEN : PEARS
' YELLOW : LIMES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
' red : strawberries
' YELLOW : LIMES
' GREEN : PEARS
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting the entire Array using the default comparer:
' black : olives
' BLUE : BERRIES
' GREEN : PEARS
' orange : cantaloupe
' purple : grapes
' red : strawberries
' YELLOW : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
' YELLOW : LIMES
' red : strawberries
' purple : grapes
' orange : cantaloupe
' GREEN : PEARS
' BLUE : BERRIES
' black : olives
注解
keys
Array 中的每个键在 items
Array中都有相应的项。 当键在排序期间重新定位时,items
Array 中的相应项将同样重新定位。 因此,items
Array 按照 keys
Array中相应键的排列方式进行排序。
keys
Array 中指定元素范围内的每个键都必须实现 IComparable 接口才能与其他每个键进行比较。
如果项数多于键,则可以进行排序,但没有相应键的项将不会进行排序。 如果键数多于项,则无法排序;执行此操作会引发 ArgumentException。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
length
。
另请参阅
- IComparable
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort(Array, Int32, Int32)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
使用 Array的每个元素的 IComparable 实现对一维 Array 中元素范围内的元素进行排序。
public:
static void Sort(Array ^ array, int index, int length);
public static void Sort (Array array, int index, int length);
static member Sort : Array * int * int -> unit
Public Shared Sub Sort (array As Array, index As Integer, length As Integer)
参数
- index
- Int32
要排序的范围的起始索引。
- length
- Int32
要排序的范围中的元素数。
例外
array
null
。
array
是多维的。
index
和 length
未在 array
中指定有效范围。
array
中的一个或多个元素不实现 IComparable 接口。
示例
下面的代码示例演示如何使用默认比较器和反转排序顺序的自定义比较器对 Array 中的值进行排序。 请注意,结果可能因当前 CultureInfo而异。
using namespace System;
using namespace System::Collections;
public ref class ReverseComparer : IComparer
{
public:
// Call CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
}
};
void DisplayValues(array<String^>^ arr)
{
for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
Console::WriteLine( " [{0}] : {1}", i, arr[ i ] );
Console::WriteLine();
}
int main()
{
// Create and initialize a new array. and a new custom comparer.
array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
"over","the","lazy","dog" };
// Instantiate the reverse comparer.
IComparer^ revComparer = gcnew ReverseComparer();
// Display the values of the Array.
Console::WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array::Sort(words, 1, 3);
Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array::Sort(words, 1, 3, revComparer);
Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array::Sort(words);
Console::WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array::Sort(words, revComparer);
Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
/*
This code produces the following output.
The Array initially contains the following values:
[0] : The
[1] : QUICK
[2] : BROWN
[3] : FOX
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the default comparer:
[0] : The
[1] : BROWN
[2] : FOX
[3] : QUICK
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the reverse case-insensitive comparer:
[0] : The
[1] : QUICK
[2] : FOX
[3] : BROWN
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting the entire Array using the default comparer:
[0] : BROWN
[1] : dog
[2] : FOX
[3] : jumps
[4] : lazy
[5] : over
[6] : QUICK
[7] : the
[8] : The
After sorting the entire Array using the reverse case-insensitive comparer:
[0] : the
[1] : The
[2] : QUICK
[3] : over
[4] : lazy
[5] : jumps
[6] : FOX
[7] : dog
[8] : BROWN
*/
using System;
using System.Collections;
public class ReverseComparer : IComparer
{
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
public int Compare(Object x, Object y)
{
return (new CaseInsensitiveComparer()).Compare(y, x );
}
}
public class Example
{
public static void Main()
{
// Create and initialize a new array.
String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" };
// Instantiate the reverse comparer.
IComparer revComparer = new ReverseComparer();
// Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3);
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer);
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array.Sort(words);
Console.WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer);
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
public static void DisplayValues(String[] arr)
{
for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
i++ ) {
Console.WriteLine( " [{0}] : {1}", i, arr[i] );
}
Console.WriteLine();
}
}
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
open System
open System.Collections
type ReverseComparer() =
interface IComparer with
member _.Compare(x, y) =
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let displayValues (arr: string []) =
for i = 0 to arr.Length - 1 do
printfn $" [{i}] : {arr[i]}"
printfn ""
// Create and initialize a new array.
let words =
[| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
"over"; "the"; "lazy"; "dog" |]
// Instantiate the reverse comparer.
let revComparer = ReverseComparer()
// Display the values of the array.
printfn "The original order of elements in the array:"
displayValues words
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
printfn "After sorting elements 1-3 by using the default comparer:"
displayValues words
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
printfn "After sorting elements 1-3 by using the reverse case-insensitive comparer:"
displayValues words
// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
Imports System.Collections
Public Class ReverseComparer : Implements IComparer
' Call CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As Object, y As Object) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function
End Class
Public Module Example
Public Sub Main()
' Create and initialize a new array.
Dim words() As String = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" }
' Instantiate a new custom comparer.
Dim revComparer As New ReverseComparer()
' Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" )
DisplayValues(words)
' Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:")
DisplayValues(words)
' Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:")
DisplayValues(words)
' Sort the entire array using the default comparer.
Array.Sort(words)
Console.WriteLine( "After sorting the entire array by using the default comparer:")
DisplayValues(words)
' Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:")
DisplayValues(words)
End Sub
Public Sub DisplayValues(arr() As String)
For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
Console.WriteLine(" [{0}] : {1}", i, arr(i))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' The original order of elements in the array:
' [0] : The
' [1] : QUICK
' [2] : BROWN
' [3] : FOX
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the default comparer:
' [0] : The
' [1] : BROWN
' [2] : FOX
' [3] : QUICK
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the reverse case-insensitive comparer:
' [0] : The
' [1] : QUICK
' [2] : FOX
' [3] : BROWN
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting the entire array by using the default comparer:
' [0] : BROWN
' [1] : dog
' [2] : FOX
' [3] : jumps
' [4] : lazy
' [5] : over
' [6] : QUICK
' [7] : the
' [8] : The
'
' After sorting the entire array using the reverse case-insensitive comparer:
' [0] : the
' [1] : The
' [2] : QUICK
' [3] : over
' [4] : lazy
' [5] : jumps
' [6] : FOX
' [7] : dog
' [8] : BROWN
注解
array
中指定元素范围内的每个元素都必须实现 IComparable 接口才能与 array
中所有其他元素进行比较。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
length
。
另请参阅
- IComparable
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort(Array, Array, IComparer)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
public:
static void Sort(Array ^ keys, Array ^ items, System::Collections::IComparer ^ comparer);
public static void Sort (Array keys, Array items, System.Collections.IComparer comparer);
public static void Sort (Array keys, Array? items, System.Collections.IComparer? comparer);
static member Sort : Array * Array * System.Collections.IComparer -> unit
Public Shared Sub Sort (keys As Array, items As Array, comparer As IComparer)
参数
例外
keys
null
。
items
不 null
,keys
的长度大于 items
长度。
-或-
comparer
的实现在排序过程中导致错误。 例如,将项与自身进行比较时,comparer
可能不会返回 0。
comparer
null
,keys
Array 中的一个或多个元素不实现 IComparable 接口。
示例
以下示例演示如何对两个关联的数组进行排序,其中第一个数组包含键,第二个数组包含值。 排序是使用默认比较器和一个反转排序顺序的自定义比较器完成的。 请注意,结果可能因当前 CultureInfo而异。
using namespace System;
using namespace System::Collections;
public ref class myReverserClass: public IComparer
{
private:
// Calls CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
}
};
void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
for ( int i = 0; i < myKeys->Length; i++ )
{
Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
}
Console::WriteLine();
}
int main()
{
// Creates and initializes a new Array and a new custom comparer.
array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
IComparer^ myComparer = gcnew myReverserClass;
// Displays the values of the Array.
Console::WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array::Sort( myKeys, myValues, 1, 3 );
Console::WriteLine( "After sorting a section of the Array using the default comparer:" );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, 1, 3, myComparer );
Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array::Sort( myKeys, myValues );
Console::WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, myComparer );
Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
using System;
using System.Collections;
public class SamplesArray {
public class myReverserClass : IComparer {
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare( Object x, Object y ) {
return( (new CaseInsensitiveComparer()).Compare( y, x ) );
}
}
public static void Main() {
// Creates and initializes a new Array and a new custom comparer.
String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
IComparer myComparer = new myReverserClass();
// Displays the values of the Array.
Console.WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array.Sort( myKeys, myValues, 1, 3 );
Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, 1, 3, myComparer );
Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array.Sort( myKeys, myValues );
Console.WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, myComparer );
Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
public static void PrintKeysAndValues( String[] myKeys, String[] myValues ) {
for ( int i = 0; i < myKeys.Length; i++ ) {
Console.WriteLine( " {0,-10}: {1}", myKeys[i], myValues[i] );
}
Console.WriteLine();
}
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
open System
open System.Collections
type MyReverserClass() =
interface IComparer with
member _.Compare(x, y) =
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let printKeysAndValues (myKeys: string []) (myValues: string []) =
for i = 0 to myKeys.Length - 1 do
printfn $" {myKeys[i],-10}: {myValues[i]}"
printfn ""
// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()
// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// This code produces the following output.
// The Array initially contains the following values:
// red : strawberries
// GREEN : PEARS
// YELLOW : LIMES
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the default comparer:
// red : strawberries
// BLUE : BERRIES
// GREEN : PEARS
// YELLOW : LIMES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the reverse case-insensitive comparer:
// red : strawberries
// YELLOW : LIMES
// GREEN : PEARS
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting the entire Array using the default comparer:
// black : olives
// BLUE : BERRIES
// GREEN : PEARS
// orange : cantaloupe
// purple : grapes
// red : strawberries
// YELLOW : LIMES
//
// After sorting the entire Array using the reverse case-insensitive comparer:
// YELLOW : LIMES
// red : strawberries
// purple : grapes
// orange : cantaloupe
// GREEN : PEARS
// BLUE : BERRIES
// black : olives
Imports System.Collections
Public Class SamplesArray
Public Class myReverserClass
Implements IComparer
' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As [Object], y As [Object]) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function 'IComparer.Compare
End Class
Public Shared Sub Main()
' Creates and initializes a new Array and a new custom comparer.
Dim myKeys As [String]() = {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
Dim myValues As [String]() = {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
Dim myComparer = New myReverserClass()
' Displays the values of the Array.
Console.WriteLine("The Array initially contains the following values:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
Console.WriteLine("After sorting a section of the Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
Console.WriteLine("After sorting the entire Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
End Sub
Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])
Dim i As Integer
For i = 0 To myKeys.Length - 1
Console.WriteLine(" {0,-10}: {1}", myKeys(i), myValues(i))
Next i
Console.WriteLine()
End Sub
End Class
'This code produces the following output.
'
'The Array initially contains the following values:
' red : strawberries
' GREEN : PEARS
' YELLOW : LIMES
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the default comparer:
' red : strawberries
' BLUE : BERRIES
' GREEN : PEARS
' YELLOW : LIMES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
' red : strawberries
' YELLOW : LIMES
' GREEN : PEARS
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting the entire Array using the default comparer:
' black : olives
' BLUE : BERRIES
' GREEN : PEARS
' orange : cantaloupe
' purple : grapes
' red : strawberries
' YELLOW : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
' YELLOW : LIMES
' red : strawberries
' purple : grapes
' orange : cantaloupe
' GREEN : PEARS
' BLUE : BERRIES
' black : olives
注解
keys
Array 中的每个键在 items
Array中都有相应的项。 当键在排序期间重新定位时,items
Array 中的相应项将同样重新定位。 因此,items
Array 按照 keys
Array中相应键的排列方式进行排序。
如果 comparer
null
,则 keys
Array 中的每个键都必须实现 IComparable 接口才能与其他每个键进行比较。
如果项数多于键,则可以进行排序,但没有相应键的项将不会进行排序。 如果键数多于项,则无法排序;执行此操作会引发 ArgumentException。
如果排序未成功完成,则结果未定义。
.NET 包括下表中列出的预定义 IComparer 实现。
实现 | 描述 |
---|---|
System.Collections.CaseInsensitiveComparer | 比较任何两个对象,但对字符串执行不区分大小写的比较。 |
Comparer.Default | 使用当前区域性的排序约定比较任何两个对象。 |
Comparer.DefaultInvariant | 使用固定区域性的排序约定比较任意两个对象。 |
Comparer<T>.Default | 使用类型的默认排序顺序比较类型 T 的两个对象。 |
还可以通过向 comparer
参数提供自己的 IComparer 实现实例来支持自定义比较。 该示例通过定义一个反转默认排序顺序并执行不区分大小写的字符串比较的 IComparer 实现来执行此操作。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
是 keys
的 Length。
调用方说明
.NET Framework 4 和早期版本仅使用 Quicksort 算法。 在排序操作引发 IndexOutOfRangeException 异常,并向调用方引发 ArgumentException 异常的情况下,Quicksort 标识无效比较器。 从 .NET Framework 4.5 开始,以前引发 ArgumentException 的排序操作可能不会引发异常,因为插入排序和堆算法不会检测到无效比较器。 在大多数情况下,这适用于小于或等于 16 个元素的数组。
另请参阅
- IComparer
- IComparable
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort(Array, Array)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
使用每个键的 IComparable 实现对一维 Array 对象(一个对象包含键,另一个对象包含相应的项)基于第一个 Array 中的键。
public:
static void Sort(Array ^ keys, Array ^ items);
public static void Sort (Array keys, Array items);
public static void Sort (Array keys, Array? items);
static member Sort : Array * Array -> unit
Public Shared Sub Sort (keys As Array, items As Array)
参数
例外
keys
null
。
items
不 null
,keys
的长度大于 items
长度。
keys
Array 中的一个或多个元素不实现 IComparable 接口。
示例
以下示例演示如何对两个关联的数组进行排序,其中第一个数组包含键,第二个数组包含值。 排序是使用默认比较器和一个反转排序顺序的自定义比较器完成的。 请注意,结果可能因当前 CultureInfo而异。
using namespace System;
using namespace System::Collections;
public ref class myReverserClass: public IComparer
{
private:
// Calls CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare( Object^ x, Object^ y ) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare( y, x ));
}
};
void PrintKeysAndValues( array<String^>^myKeys, array<String^>^myValues )
{
for ( int i = 0; i < myKeys->Length; i++ )
{
Console::WriteLine( " {0, -10}: {1}", myKeys[ i ], myValues[ i ] );
}
Console::WriteLine();
}
int main()
{
// Creates and initializes a new Array and a new custom comparer.
array<String^>^myKeys = {"red","GREEN","YELLOW","BLUE","purple","black","orange"};
array<String^>^myValues = {"strawberries","PEARS","LIMES","BERRIES","grapes","olives","cantaloupe"};
IComparer^ myComparer = gcnew myReverserClass;
// Displays the values of the Array.
Console::WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array::Sort( myKeys, myValues, 1, 3 );
Console::WriteLine( "After sorting a section of the Array using the default comparer:" );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, 1, 3, myComparer );
Console::WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array::Sort( myKeys, myValues );
Console::WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array::Sort( myKeys, myValues, myComparer );
Console::WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
using System;
using System.Collections;
public class SamplesArray {
public class myReverserClass : IComparer {
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
int IComparer.Compare( Object x, Object y ) {
return( (new CaseInsensitiveComparer()).Compare( y, x ) );
}
}
public static void Main() {
// Creates and initializes a new Array and a new custom comparer.
String[] myKeys = { "red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange" };
String[] myValues = { "strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe" };
IComparer myComparer = new myReverserClass();
// Displays the values of the Array.
Console.WriteLine( "The Array initially contains the following values:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the default comparer.
Array.Sort( myKeys, myValues, 1, 3 );
Console.WriteLine( "After sorting a section of the Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, 1, 3, myComparer );
Console.WriteLine( "After sorting a section of the Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the default comparer.
Array.Sort( myKeys, myValues );
Console.WriteLine( "After sorting the entire Array using the default comparer:" );
PrintKeysAndValues( myKeys, myValues );
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort( myKeys, myValues, myComparer );
Console.WriteLine( "After sorting the entire Array using the reverse case-insensitive comparer:" );
PrintKeysAndValues( myKeys, myValues );
}
public static void PrintKeysAndValues( String[] myKeys, String[] myValues ) {
for ( int i = 0; i < myKeys.Length; i++ ) {
Console.WriteLine( " {0,-10}: {1}", myKeys[i], myValues[i] );
}
Console.WriteLine();
}
}
/*
This code produces the following output.
The Array initially contains the following values:
red : strawberries
GREEN : PEARS
YELLOW : LIMES
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the default comparer:
red : strawberries
BLUE : BERRIES
GREEN : PEARS
YELLOW : LIMES
purple : grapes
black : olives
orange : cantaloupe
After sorting a section of the Array using the reverse case-insensitive comparer:
red : strawberries
YELLOW : LIMES
GREEN : PEARS
BLUE : BERRIES
purple : grapes
black : olives
orange : cantaloupe
After sorting the entire Array using the default comparer:
black : olives
BLUE : BERRIES
GREEN : PEARS
orange : cantaloupe
purple : grapes
red : strawberries
YELLOW : LIMES
After sorting the entire Array using the reverse case-insensitive comparer:
YELLOW : LIMES
red : strawberries
purple : grapes
orange : cantaloupe
GREEN : PEARS
BLUE : BERRIES
black : olives
*/
open System
open System.Collections
type MyReverserClass() =
interface IComparer with
member _.Compare(x, y) =
// Calls CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let printKeysAndValues (myKeys: string []) (myValues: string []) =
for i = 0 to myKeys.Length - 1 do
printfn $" {myKeys[i],-10}: {myValues[i]}"
printfn ""
// Creates and initializes a new Array and a new custom comparer.
let myKeys = [| "red"; "GREEN"; "YELLOW"; "BLUE"; "purple"; "black"; "orange" |]
let myValues = [| "strawberries"; "PEARS"; "LIMES"; "BERRIES"; "grapes"; "olives"; "cantaloupe" |]
let myComparer = MyReverserClass()
// Displays the values of the Array.
printfn "The Array initially contains the following values:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
printfn "After sorting a section of the Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
printfn "After sorting a section of the Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
printfn "After sorting the entire Array using the default comparer:"
printKeysAndValues myKeys myValues
// Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
printfn "After sorting the entire Array using the reverse case-insensitive comparer:"
printKeysAndValues myKeys myValues
// This code produces the following output.
// The Array initially contains the following values:
// red : strawberries
// GREEN : PEARS
// YELLOW : LIMES
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the default comparer:
// red : strawberries
// BLUE : BERRIES
// GREEN : PEARS
// YELLOW : LIMES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting a section of the Array using the reverse case-insensitive comparer:
// red : strawberries
// YELLOW : LIMES
// GREEN : PEARS
// BLUE : BERRIES
// purple : grapes
// black : olives
// orange : cantaloupe
//
// After sorting the entire Array using the default comparer:
// black : olives
// BLUE : BERRIES
// GREEN : PEARS
// orange : cantaloupe
// purple : grapes
// red : strawberries
// YELLOW : LIMES
//
// After sorting the entire Array using the reverse case-insensitive comparer:
// YELLOW : LIMES
// red : strawberries
// purple : grapes
// orange : cantaloupe
// GREEN : PEARS
// BLUE : BERRIES
// black : olives
Imports System.Collections
Public Class SamplesArray
Public Class myReverserClass
Implements IComparer
' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As [Object], y As [Object]) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function 'IComparer.Compare
End Class
Public Shared Sub Main()
' Creates and initializes a new Array and a new custom comparer.
Dim myKeys As [String]() = {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
Dim myValues As [String]() = {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
Dim myComparer = New myReverserClass()
' Displays the values of the Array.
Console.WriteLine("The Array initially contains the following values:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the default comparer.
Array.Sort(myKeys, myValues, 1, 3)
Console.WriteLine("After sorting a section of the Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts a section of the Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, 1, 3, myComparer)
Console.WriteLine("After sorting a section of the Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the default comparer.
Array.Sort(myKeys, myValues)
Console.WriteLine("After sorting the entire Array using the default comparer:")
PrintKeysAndValues(myKeys, myValues)
' Sorts the entire Array using the reverse case-insensitive comparer.
Array.Sort(myKeys, myValues, myComparer)
Console.WriteLine("After sorting the entire Array using the reverse case-insensitive comparer:")
PrintKeysAndValues(myKeys, myValues)
End Sub
Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])
Dim i As Integer
For i = 0 To myKeys.Length - 1
Console.WriteLine(" {0,-10}: {1}", myKeys(i), myValues(i))
Next i
Console.WriteLine()
End Sub
End Class
'This code produces the following output.
'
'The Array initially contains the following values:
' red : strawberries
' GREEN : PEARS
' YELLOW : LIMES
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the default comparer:
' red : strawberries
' BLUE : BERRIES
' GREEN : PEARS
' YELLOW : LIMES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
' red : strawberries
' YELLOW : LIMES
' GREEN : PEARS
' BLUE : BERRIES
' purple : grapes
' black : olives
' orange : cantaloupe
'
'After sorting the entire Array using the default comparer:
' black : olives
' BLUE : BERRIES
' GREEN : PEARS
' orange : cantaloupe
' purple : grapes
' red : strawberries
' YELLOW : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
' YELLOW : LIMES
' red : strawberries
' purple : grapes
' orange : cantaloupe
' GREEN : PEARS
' BLUE : BERRIES
' black : olives
注解
keys
Array 中的每个键在 items
Array中都有相应的项。 当键在排序期间重新定位时,items
Array 中的相应项将同样重新定位。 因此,items
Array 按照 keys
Array中相应键的排列方式进行排序。
keys
Array 中的每个键都必须实现 IComparable 接口才能与其他键进行比较。
如果项数多于键,则可以进行排序,但没有相应键的项将不会进行排序。 如果键数多于项,则无法排序;执行此操作会引发 ArgumentException。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
是 keys
的 Length。
另请参阅
- IComparable
- BinarySearch
- IDictionary
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort(Array)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
使用 Array每个元素的 IComparable 实现对整个一维 Array 中的元素进行排序。
public:
static void Sort(Array ^ array);
public static void Sort (Array array);
static member Sort : Array -> unit
Public Shared Sub Sort (array As Array)
参数
例外
array
null
。
array
是多维的。
array
中的一个或多个元素不实现 IComparable 接口。
示例
下面的代码示例演示如何使用默认比较器和反转排序顺序的自定义比较器对 Array 中的值进行排序。 请注意,结果可能因当前 CultureInfo而异。
using namespace System;
using namespace System::Collections;
public ref class ReverseComparer : IComparer
{
public:
// Call CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
}
};
void DisplayValues(array<String^>^ arr)
{
for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
Console::WriteLine( " [{0}] : {1}", i, arr[ i ] );
Console::WriteLine();
}
int main()
{
// Create and initialize a new array. and a new custom comparer.
array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
"over","the","lazy","dog" };
// Instantiate the reverse comparer.
IComparer^ revComparer = gcnew ReverseComparer();
// Display the values of the Array.
Console::WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array::Sort(words, 1, 3);
Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array::Sort(words, 1, 3, revComparer);
Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array::Sort(words);
Console::WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array::Sort(words, revComparer);
Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
/*
This code produces the following output.
The Array initially contains the following values:
[0] : The
[1] : QUICK
[2] : BROWN
[3] : FOX
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the default comparer:
[0] : The
[1] : BROWN
[2] : FOX
[3] : QUICK
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the reverse case-insensitive comparer:
[0] : The
[1] : QUICK
[2] : FOX
[3] : BROWN
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting the entire Array using the default comparer:
[0] : BROWN
[1] : dog
[2] : FOX
[3] : jumps
[4] : lazy
[5] : over
[6] : QUICK
[7] : the
[8] : The
After sorting the entire Array using the reverse case-insensitive comparer:
[0] : the
[1] : The
[2] : QUICK
[3] : over
[4] : lazy
[5] : jumps
[6] : FOX
[7] : dog
[8] : BROWN
*/
using System;
using System.Collections;
public class ReverseComparer : IComparer
{
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
public int Compare(Object x, Object y)
{
return (new CaseInsensitiveComparer()).Compare(y, x );
}
}
public class Example
{
public static void Main()
{
// Create and initialize a new array.
String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" };
// Instantiate the reverse comparer.
IComparer revComparer = new ReverseComparer();
// Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3);
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer);
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array.Sort(words);
Console.WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer);
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
public static void DisplayValues(String[] arr)
{
for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
i++ ) {
Console.WriteLine( " [{0}] : {1}", i, arr[i] );
}
Console.WriteLine();
}
}
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
open System
open System.Collections
type ReverseComparer() =
interface IComparer with
member _.Compare(x, y) =
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let displayValues (arr: string []) =
for i = 0 to arr.Length - 1 do
printfn $" [{i}] : {arr[i]}"
printfn ""
// Create and initialize a new array.
let words =
[| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
"over"; "the"; "lazy"; "dog" |]
// Instantiate the reverse comparer.
let revComparer = ReverseComparer()
// Display the values of the array.
printfn "The original order of elements in the array:"
displayValues words
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
printfn "After sorting elements 1-3 by using the default comparer:"
displayValues words
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
printfn "After sorting elements 1-3 by using the reverse case-insensitive comparer:"
displayValues words
// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
Imports System.Collections
Public Class ReverseComparer : Implements IComparer
' Call CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As Object, y As Object) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function
End Class
Public Module Example
Public Sub Main()
' Create and initialize a new array.
Dim words() As String = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" }
' Instantiate a new custom comparer.
Dim revComparer As New ReverseComparer()
' Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" )
DisplayValues(words)
' Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:")
DisplayValues(words)
' Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:")
DisplayValues(words)
' Sort the entire array using the default comparer.
Array.Sort(words)
Console.WriteLine( "After sorting the entire array by using the default comparer:")
DisplayValues(words)
' Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:")
DisplayValues(words)
End Sub
Public Sub DisplayValues(arr() As String)
For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
Console.WriteLine(" [{0}] : {1}", i, arr(i))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' The original order of elements in the array:
' [0] : The
' [1] : QUICK
' [2] : BROWN
' [3] : FOX
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the default comparer:
' [0] : The
' [1] : BROWN
' [2] : FOX
' [3] : QUICK
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the reverse case-insensitive comparer:
' [0] : The
' [1] : QUICK
' [2] : FOX
' [3] : BROWN
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting the entire array by using the default comparer:
' [0] : BROWN
' [1] : dog
' [2] : FOX
' [3] : jumps
' [4] : lazy
' [5] : over
' [6] : QUICK
' [7] : the
' [8] : The
'
' After sorting the entire array using the reverse case-insensitive comparer:
' [0] : the
' [1] : The
' [2] : QUICK
' [3] : over
' [4] : lazy
' [5] : jumps
' [6] : FOX
' [7] : dog
' [8] : BROWN
注解
array
的每个元素都必须实现 IComparable 接口才能与 array
中所有其他元素进行比较。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
是 array
的 Length。
另请参阅
- IComparable
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort(Array, IComparer)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
public:
static void Sort(Array ^ array, System::Collections::IComparer ^ comparer);
public static void Sort (Array array, System.Collections.IComparer comparer);
public static void Sort (Array array, System.Collections.IComparer? comparer);
static member Sort : Array * System.Collections.IComparer -> unit
Public Shared Sub Sort (array As Array, comparer As IComparer)
参数
- array
- Array
要排序的一维数组。
例外
array
null
。
array
是多维的。
comparer
null
,array
中的一个或多个元素不实现 IComparable 接口。
comparer
的实现在排序过程中导致错误。 例如,将项与自身进行比较时,comparer
可能不会返回 0。
示例
以下示例使用默认比较器对字符串数组中的值进行排序。 它还定义了一个名为 ReverseComparer
的自定义 IComparer 实现,该实现在执行不区分大小写的字符串比较时反转对象的默认排序顺序。 请注意,输出可能因当前区域性而异。
using namespace System;
using namespace System::Collections;
public ref class ReverseComparer : IComparer
{
public:
// Call CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
}
};
void DisplayValues(array<String^>^ arr)
{
for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
Console::WriteLine( " [{0}] : {1}", i, arr[ i ] );
Console::WriteLine();
}
int main()
{
// Create and initialize a new array. and a new custom comparer.
array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
"over","the","lazy","dog" };
// Instantiate the reverse comparer.
IComparer^ revComparer = gcnew ReverseComparer();
// Display the values of the Array.
Console::WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array::Sort(words, 1, 3);
Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array::Sort(words, 1, 3, revComparer);
Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array::Sort(words);
Console::WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array::Sort(words, revComparer);
Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
/*
This code produces the following output.
The Array initially contains the following values:
[0] : The
[1] : QUICK
[2] : BROWN
[3] : FOX
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the default comparer:
[0] : The
[1] : BROWN
[2] : FOX
[3] : QUICK
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the reverse case-insensitive comparer:
[0] : The
[1] : QUICK
[2] : FOX
[3] : BROWN
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting the entire Array using the default comparer:
[0] : BROWN
[1] : dog
[2] : FOX
[3] : jumps
[4] : lazy
[5] : over
[6] : QUICK
[7] : the
[8] : The
After sorting the entire Array using the reverse case-insensitive comparer:
[0] : the
[1] : The
[2] : QUICK
[3] : over
[4] : lazy
[5] : jumps
[6] : FOX
[7] : dog
[8] : BROWN
*/
using System;
using System.Collections;
public class ReverseComparer : IComparer
{
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
public int Compare(Object x, Object y)
{
return (new CaseInsensitiveComparer()).Compare(y, x );
}
}
public class Example
{
public static void Main()
{
// Create and initialize a new array.
String[] words = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" };
// Instantiate the reverse comparer.
IComparer revComparer = new ReverseComparer();
// Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3);
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer);
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array.Sort(words);
Console.WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer);
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
public static void DisplayValues(String[] arr)
{
for ( int i = arr.GetLowerBound(0); i <= arr.GetUpperBound(0);
i++ ) {
Console.WriteLine( " [{0}] : {1}", i, arr[i] );
}
Console.WriteLine();
}
}
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
open System
open System.Collections
type ReverseComparer() =
interface IComparer with
member _.Compare(x, y) =
// Call CaseInsensitiveComparer.Compare with the parameters reversed.
CaseInsensitiveComparer().Compare(y, x)
let displayValues (arr: string []) =
for i = 0 to arr.Length - 1 do
printfn $" [{i}] : {arr[i]}"
printfn ""
// Create and initialize a new array.
let words =
[| "The"; "QUICK"; "BROWN"; "FOX"; "jumps"
"over"; "the"; "lazy"; "dog" |]
// Instantiate the reverse comparer.
let revComparer = ReverseComparer()
// Display the values of the array.
printfn "The original order of elements in the array:"
displayValues words
// Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
printfn "After sorting elements 1-3 by using the default comparer:"
displayValues words
// Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
printfn "After sorting elements 1-3 by using the reverse case-insensitive comparer:"
displayValues words
// Sort the entire array using the default comparer.
Array.Sort words
printfn "After sorting the entire array by using the default comparer:"
displayValues words
// Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
printfn "After sorting the entire array using the reverse case-insensitive comparer:"
displayValues words
// The example displays the following output:
// The original order of elements in the array:
// [0] : The
// [1] : QUICK
// [2] : BROWN
// [3] : FOX
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the default comparer:
// [0] : The
// [1] : BROWN
// [2] : FOX
// [3] : QUICK
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting elements 1-3 by using the reverse case-insensitive comparer:
// [0] : The
// [1] : QUICK
// [2] : FOX
// [3] : BROWN
// [4] : jumps
// [5] : over
// [6] : the
// [7] : lazy
// [8] : dog
//
// After sorting the entire array by using the default comparer:
// [0] : BROWN
// [1] : dog
// [2] : FOX
// [3] : jumps
// [4] : lazy
// [5] : over
// [6] : QUICK
// [7] : the
// [8] : The
//
// After sorting the entire array using the reverse case-insensitive comparer:
// [0] : the
// [1] : The
// [2] : QUICK
// [3] : over
// [4] : lazy
// [5] : jumps
// [6] : FOX
// [7] : dog
// [8] : BROWN
Imports System.Collections
Public Class ReverseComparer : Implements IComparer
' Call CaseInsensitiveComparer.Compare with the parameters reversed.
Function Compare(x As Object, y As Object) As Integer _
Implements IComparer.Compare
Return New CaseInsensitiveComparer().Compare(y, x)
End Function
End Class
Public Module Example
Public Sub Main()
' Create and initialize a new array.
Dim words() As String = { "The", "QUICK", "BROWN", "FOX", "jumps",
"over", "the", "lazy", "dog" }
' Instantiate a new custom comparer.
Dim revComparer As New ReverseComparer()
' Display the values of the array.
Console.WriteLine( "The original order of elements in the array:" )
DisplayValues(words)
' Sort a section of the array using the default comparer.
Array.Sort(words, 1, 3)
Console.WriteLine( "After sorting elements 1-3 by using the default comparer:")
DisplayValues(words)
' Sort a section of the array using the reverse case-insensitive comparer.
Array.Sort(words, 1, 3, revComparer)
Console.WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:")
DisplayValues(words)
' Sort the entire array using the default comparer.
Array.Sort(words)
Console.WriteLine( "After sorting the entire array by using the default comparer:")
DisplayValues(words)
' Sort the entire array by using the reverse case-insensitive comparer.
Array.Sort(words, revComparer)
Console.WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:")
DisplayValues(words)
End Sub
Public Sub DisplayValues(arr() As String)
For i As Integer = arr.GetLowerBound(0) To arr.GetUpperBound(0)
Console.WriteLine(" [{0}] : {1}", i, arr(i))
Next
Console.WriteLine()
End Sub
End Module
' The example displays the following output:
' The original order of elements in the array:
' [0] : The
' [1] : QUICK
' [2] : BROWN
' [3] : FOX
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the default comparer:
' [0] : The
' [1] : BROWN
' [2] : FOX
' [3] : QUICK
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting elements 1-3 by using the reverse case-insensitive comparer:
' [0] : The
' [1] : QUICK
' [2] : FOX
' [3] : BROWN
' [4] : jumps
' [5] : over
' [6] : the
' [7] : lazy
' [8] : dog
'
' After sorting the entire array by using the default comparer:
' [0] : BROWN
' [1] : dog
' [2] : FOX
' [3] : jumps
' [4] : lazy
' [5] : over
' [6] : QUICK
' [7] : the
' [8] : The
'
' After sorting the entire array using the reverse case-insensitive comparer:
' [0] : the
' [1] : The
' [2] : QUICK
' [3] : over
' [4] : lazy
' [5] : jumps
' [6] : FOX
' [7] : dog
' [8] : BROWN
注解
如果 comparer
null
,array
的每个元素都必须实现 IComparable 接口才能与 array
中所有其他元素进行比较。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
是 array
的 Length。
.NET 包括下表中列出的预定义 IComparer 实现。
实现 | 描述 |
---|---|
System.Collections.CaseInsensitiveComparer | 比较任何两个对象,但对字符串执行不区分大小写的比较。 |
Comparer.Default | 使用当前区域性的排序约定比较任何两个对象。 |
Comparer.DefaultInvariant | 使用固定区域性的排序约定比较任意两个对象。 |
Comparer<T>.Default | 使用类型的默认排序顺序比较类型 T 的两个对象。 |
还可以通过向 comparer
参数提供自己的 IComparer 实现实例来支持自定义比较。 该示例通过定义一个 ReverseComparer
类来反转类型实例的默认排序顺序,并执行不区分大小写的字符串比较。
调用方说明
.NET Framework 4 和早期版本仅使用 Quicksort 算法。 在排序操作引发 IndexOutOfRangeException 异常,并向调用方引发 ArgumentException 异常的情况下,Quicksort 标识无效比较器。 从 .NET Framework 4.5 开始,以前引发 ArgumentException 的排序操作可能不会引发异常,因为插入排序和堆算法不会检测到无效比较器。 在大多数情况下,这适用于小于或等于 16 个元素的数组。
另请参阅
- IComparer
- IComparable
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort<T>(T[])
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
使用 Array每个元素的 IComparable<T> 泛型接口实现对整个 Array 中的元素进行排序。
public:
generic <typename T>
static void Sort(cli::array <T> ^ array);
public static void Sort<T> (T[] array);
static member Sort : 'T[] -> unit
Public Shared Sub Sort(Of T) (array As T())
类型参数
- T
数组元素的类型。
参数
- array
- T[]
要排序的从零开始的一维 Array。
例外
array
null
。
array
中的一个或多个元素不实现 IComparable<T> 泛型接口。
示例
下面的代码示例演示 Sort<T>(T[]) 泛型方法重载和 BinarySearch<T>(T[], T) 泛型方法重载。 不按特定顺序创建字符串数组。
该数组将再次显示、排序和显示。
注意
对 Sort 和 BinarySearch 泛型方法的调用与其非泛型方法的调用不同,因为 Visual Basic、C# 和C++从第一个参数的类型推断泛型类型参数的类型。 如果使用 Ildasm.exe(IL 反汇编程序) 检查Microsoft中间语言(MSIL),可以看到正在调用泛型方法。
然后,BinarySearch<T>(T[], T) 泛型方法重载用于搜索两个字符串,一个字符串不在数组中,一个不在数组中。 将 BinarySearch 方法的数组和返回值传递给 ShowWhere
泛型方法,如果找到字符串,则显示索引值;否则,搜索字符串在数组中时将介于其之间的元素。 如果字符串不是数组 n,则索引为负值,因此 ShowWhere
方法采用按位补号(C# 和 Visual C++ 中的 ~ 运算符,Xor
-1 在 Visual Basic 中)获取列表中大于搜索字符串的第一个元素的索引。
using namespace System;
using namespace System::Collections::Generic;
generic<typename T> void ShowWhere(array<T>^ arr, int index)
{
if (index<0)
{
// If the index is negative, it represents the bitwise
// complement of the next larger element in the array.
//
index = ~index;
Console::Write("Not found. Sorts between: ");
if (index == 0)
Console::Write("beginning of array and ");
else
Console::Write("{0} and ", arr[index-1]);
if (index == arr->Length)
Console::WriteLine("end of array.");
else
Console::WriteLine("{0}.", arr[index]);
}
else
{
Console::WriteLine("Found at index {0}.", index);
}
};
void main()
{
array<String^>^ dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Tyrannosaurus",
"Mamenchisaurus",
"Deinonychus",
"Edmontosaurus"};
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nSort");
Array::Sort(dinosaurs);
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nBinarySearch for 'Coelophysis':");
int index = Array::BinarySearch(dinosaurs, "Coelophysis");
ShowWhere(dinosaurs, index);
Console::WriteLine("\nBinarySearch for 'Tyrannosaurus':");
index = Array::BinarySearch(dinosaurs, "Tyrannosaurus");
ShowWhere(dinosaurs, index);
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus
Sort
Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus
BinarySearch for 'Coelophysis':
Not found. Sorts between: Amargasaurus and Deinonychus.
BinarySearch for 'Tyrannosaurus':
Found at index 5.
*/
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
string[] dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Tyrannosaurus",
"Mamenchisaurus",
"Deinonychus",
"Edmontosaurus"};
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nSort");
Array.Sort(dinosaurs);
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nBinarySearch for 'Coelophysis':");
int index = Array.BinarySearch(dinosaurs, "Coelophysis");
ShowWhere(dinosaurs, index);
Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus");
ShowWhere(dinosaurs, index);
}
private static void ShowWhere<T>(T[] array, int index)
{
if (index<0)
{
// If the index is negative, it represents the bitwise
// complement of the next larger element in the array.
//
index = ~index;
Console.Write("Not found. Sorts between: ");
if (index == 0)
Console.Write("beginning of array and ");
else
Console.Write("{0} and ", array[index-1]);
if (index == array.Length)
Console.WriteLine("end of array.");
else
Console.WriteLine("{0}.", array[index]);
}
else
{
Console.WriteLine("Found at index {0}.", index);
}
}
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus
Sort
Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus
BinarySearch for 'Coelophysis':
Not found. Sorts between: Amargasaurus and Deinonychus.
BinarySearch for 'Tyrannosaurus':
Found at index 5.
*/
open System
let showWhere (array: 'a []) index =
if index < 0 then
// If the index is negative, it represents the bitwise
// complement of the next larger element in the array.
let index = ~~~index
printf "Not found. Sorts between: "
if index = 0 then
printf "beginning of array and "
else
printf $"{array[index - 1]} and "
if index = array.Length then
printfn "end of array."
else
printfn $"{array[index]}."
else
printfn $"Found at index {index}."
let dinosaurs =
[| "Pachycephalosaurus"
"Amargasaurus"
"Tyrannosaurus"
"Mamenchisaurus"
"Deinonychus"
"Edmontosaurus" |]
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
printfn "\nSort"
Array.Sort dinosaurs
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
printfn "\nBinarySearch for 'Coelophysis':"
let index = Array.BinarySearch(dinosaurs, "Coelophysis")
showWhere dinosaurs index
printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus")
|> showWhere dinosaurs
// This code example produces the following output:
//
// Pachycephalosaurus
// Amargasaurus
// Tyrannosaurus
// Mamenchisaurus
// Deinonychus
// Edmontosaurus
//
// Sort
//
// Amargasaurus
// Deinonychus
// Edmontosaurus
// Mamenchisaurus
// Pachycephalosaurus
// Tyrannosaurus
//
// BinarySearch for 'Coelophysis':
// Not found. Sorts between: Amargasaurus and Deinonychus.
//
// BinarySearch for 'Tyrannosaurus':
// Found at index 5.
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Pachycephalosaurus", _
"Amargasaurus", _
"Tyrannosaurus", _
"Mamenchisaurus", _
"Deinonychus", _
"Edmontosaurus" }
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & "Sort")
Array.Sort(dinosaurs)
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & _
"BinarySearch for 'Coelophysis':")
Dim index As Integer = _
Array.BinarySearch(dinosaurs, "Coelophysis")
ShowWhere(dinosaurs, index)
Console.WriteLine(vbLf & _
"BinarySearch for 'Tyrannosaurus':")
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus")
ShowWhere(dinosaurs, index)
End Sub
Private Shared Sub ShowWhere(Of T) _
(ByVal array() As T, ByVal index As Integer)
If index < 0 Then
' If the index is negative, it represents the bitwise
' complement of the next larger element in the array.
'
index = index Xor -1
Console.Write("Not found. Sorts between: ")
If index = 0 Then
Console.Write("beginning of array and ")
Else
Console.Write("{0} and ", array(index - 1))
End If
If index = array.Length Then
Console.WriteLine("end of array.")
Else
Console.WriteLine("{0}.", array(index))
End If
Else
Console.WriteLine("Found at index {0}.", index)
End If
End Sub
End Class
' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Tyrannosaurus
'Mamenchisaurus
'Deinonychus
'Edmontosaurus
'
'Sort
'
'Amargasaurus
'Deinonychus
'Edmontosaurus
'Mamenchisaurus
'Pachycephalosaurus
'Tyrannosaurus
'
'BinarySearch for 'Coelophysis':
'Not found. Sorts between: Amargasaurus and Deinonychus.
'
'BinarySearch for 'Tyrannosaurus':
'Found at index 5.
注解
array
的每个元素都必须实现 IComparable<T> 泛型接口,才能与 array
中所有其他元素进行比较。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
是 array
的 Length。
另请参阅
- IComparable<T>
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort<T>(T[], IComparer<T>)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
使用指定的 IComparer<T> 泛型接口对 Array 中的元素进行排序。
public:
generic <typename T>
static void Sort(cli::array <T> ^ array, System::Collections::Generic::IComparer<T> ^ comparer);
public static void Sort<T> (T[] array, System.Collections.Generic.IComparer<T> comparer);
public static void Sort<T> (T[] array, System.Collections.Generic.IComparer<T>? comparer);
static member Sort : 'T[] * System.Collections.Generic.IComparer<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), comparer As IComparer(Of T))
类型参数
- T
数组元素的类型。
参数
- array
- T[]
要排序的一维零基 Array。
- comparer
- IComparer<T>
比较元素时要使用的 IComparer<T> 泛型接口实现,或 null
使用每个元素的 IComparable<T> 泛型接口实现。
例外
array
null
。
comparer
null
,array
中的一个或多个元素不实现 IComparable<T> 泛型接口。
comparer
的实现在排序过程中导致错误。 例如,将项与自身进行比较时,comparer
可能不会返回 0。
示例
下面的代码示例演示 Sort<T>(T[], IComparer<T>) 泛型方法重载和 BinarySearch<T>(T[], T, IComparer<T>) 泛型方法重载。
该代码示例为名为 ReverseCompare
的字符串定义一个替代比较器,该比较器实现 visual Basic 中的 IComparer<string>
(IComparer(Of String)
,在 Visual C++) 泛型接口中 IComparer<String^>
。 比较器调用 CompareTo(String) 方法,反转比较器的顺序,使字符串排序高到低,而不是低到高。
该数组将再次显示、排序和显示。 必须对数组进行排序才能使用 BinarySearch 方法。
注意
对 Sort<T>(T[], IComparer<T>) 和 BinarySearch<T>(T[], T, IComparer<T>) 泛型方法的调用与其非泛型方法的调用不同,因为 Visual Basic、C# 和C++从第一个参数的类型推断泛型类型参数的类型。 如果使用 Ildasm.exe(IL 反汇编程序) 检查Microsoft中间语言(MSIL),可以看到正在调用泛型方法。
然后,BinarySearch<T>(T[], T, IComparer<T>) 泛型方法重载用于搜索两个字符串,一个字符串不在数组中,一个不在数组中。 将 BinarySearch<T>(T[], T, IComparer<T>) 方法的数组和返回值传递给 ShowWhere
泛型方法,如果找到字符串,则显示索引值;否则,搜索字符串在数组中时将介于其之间的元素。 如果字符串不是数组 n,则索引为负值,因此 ShowWhere
方法采用按位补号(C# 和 Visual C++ 中的 ~ 运算符,Xor
-1 在 Visual Basic 中)获取列表中大于搜索字符串的第一个元素的索引。
using namespace System;
using namespace System::Collections::Generic;
public ref class ReverseComparer: IComparer<String^>
{
public:
virtual int Compare(String^ x, String^ y)
{
// Compare y and x in reverse order.
return y->CompareTo(x);
}
};
generic<typename T> void ShowWhere(array<T>^ arr, int index)
{
if (index<0)
{
// If the index is negative, it represents the bitwise
// complement of the next larger element in the array.
//
index = ~index;
Console::Write("Not found. Sorts between: ");
if (index == 0)
Console::Write("beginning of array and ");
else
Console::Write("{0} and ", arr[index-1]);
if (index == arr->Length)
Console::WriteLine("end of array.");
else
Console::WriteLine("{0}.", arr[index]);
}
else
{
Console::WriteLine("Found at index {0}.", index);
}
};
void main()
{
array<String^>^ dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Tyrannosaurus",
"Mamenchisaurus",
"Deinonychus",
"Edmontosaurus"};
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
ReverseComparer^ rc = gcnew ReverseComparer();
Console::WriteLine("\nSort");
Array::Sort(dinosaurs, rc);
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nBinarySearch for 'Coelophysis':");
int index = Array::BinarySearch(dinosaurs, "Coelophysis", rc);
ShowWhere(dinosaurs, index);
Console::WriteLine("\nBinarySearch for 'Tyrannosaurus':");
index = Array::BinarySearch(dinosaurs, "Tyrannosaurus", rc);
ShowWhere(dinosaurs, index);
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus
Sort
Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus
BinarySearch for 'Coelophysis':
Not found. Sorts between: Deinonychus and Amargasaurus.
BinarySearch for 'Tyrannosaurus':
Found at index 0.
*/
using System;
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Tyrannosaurus",
"Mamenchisaurus",
"Deinonychus",
"Edmontosaurus"};
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
ReverseComparer rc = new ReverseComparer();
Console.WriteLine("\nSort");
Array.Sort(dinosaurs, rc);
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nBinarySearch for 'Coelophysis':");
int index = Array.BinarySearch(dinosaurs, "Coelophysis", rc);
ShowWhere(dinosaurs, index);
Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc);
ShowWhere(dinosaurs, index);
}
private static void ShowWhere<T>(T[] array, int index)
{
if (index<0)
{
// If the index is negative, it represents the bitwise
// complement of the next larger element in the array.
//
index = ~index;
Console.Write("Not found. Sorts between: ");
if (index == 0)
Console.Write("beginning of array and ");
else
Console.Write("{0} and ", array[index-1]);
if (index == array.Length)
Console.WriteLine("end of array.");
else
Console.WriteLine("{0}.", array[index]);
}
else
{
Console.WriteLine("Found at index {0}.", index);
}
}
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus
Sort
Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus
BinarySearch for 'Coelophysis':
Not found. Sorts between: Deinonychus and Amargasaurus.
BinarySearch for 'Tyrannosaurus':
Found at index 0.
*/
open System
open System.Collections.Generic
type ReverseComparer() =
interface IComparer<string> with
member _.Compare(x, y) =
// Compare y and x in reverse order.
y.CompareTo x
let showWhere (array: 'a []) index =
if index < 0 then
// If the index is negative, it represents the bitwise
// complement of the next larger element in the array.
let index = ~~~index
printf "Not found. Sorts between: "
if index = 0 then
printf "beginning of array and "
else
printf $"{array[index - 1]} and "
if index = array.Length then
printfn "end of array."
else
printfn $"{array[index]}."
else
printfn $"Found at index {index}."
let dinosaurs =
[| "Pachycephalosaurus"
"Amargasaurus"
"Tyrannosaurus"
"Mamenchisaurus"
"Deinonychus"
"Edmontosaurus" |]
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
let rc = ReverseComparer()
printfn "\nSort"
Array.Sort(dinosaurs, rc)
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
printfn "\nBinarySearch for 'Coelophysis':"
Array.BinarySearch(dinosaurs, "Coelophysis", rc)
|> showWhere dinosaurs
printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
|> showWhere dinosaurs
// This code example produces the following output:
// Pachycephalosaurus
// Amargasaurus
// Tyrannosaurus
// Mamenchisaurus
// Deinonychus
// Edmontosaurus
//
// Sort
//
// Tyrannosaurus
// Pachycephalosaurus
// Mamenchisaurus
// Edmontosaurus
// Deinonychus
// Amargasaurus
//
// BinarySearch for 'Coelophysis':
// Not found. Sorts between: Deinonychus and Amargasaurus.
//
// BinarySearch for 'Tyrannosaurus':
// Found at index 0.
Imports System.Collections.Generic
Public Class ReverseComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, _
ByVal y As String) As Integer _
Implements IComparer(Of String).Compare
' Compare y and x in reverse order.
Return y.CompareTo(x)
End Function
End Class
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Pachycephalosaurus", _
"Amargasaurus", _
"Tyrannosaurus", _
"Mamenchisaurus", _
"Deinonychus", _
"Edmontosaurus" }
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Dim rc As New ReverseComparer()
Console.WriteLine(vbLf & "Sort")
Array.Sort(dinosaurs, rc)
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & _
"BinarySearch for 'Coelophysis':")
Dim index As Integer = _
Array.BinarySearch(dinosaurs, "Coelophysis", rc)
ShowWhere(dinosaurs, index)
Console.WriteLine(vbLf & _
"BinarySearch for 'Tyrannosaurus':")
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
ShowWhere(dinosaurs, index)
End Sub
Private Shared Sub ShowWhere(Of T) _
(ByVal array() As T, ByVal index As Integer)
If index < 0 Then
' If the index is negative, it represents the bitwise
' complement of the next larger element in the array.
'
index = index Xor -1
Console.Write("Not found. Sorts between: ")
If index = 0 Then
Console.Write("beginning of array and ")
Else
Console.Write("{0} and ", array(index - 1))
End If
If index = array.Length Then
Console.WriteLine("end of array.")
Else
Console.WriteLine("{0}.", array(index))
End If
Else
Console.WriteLine("Found at index {0}.", index)
End If
End Sub
End Class
' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Tyrannosaurus
'Mamenchisaurus
'Deinonychus
'Edmontosaurus
'
'Sort
'
'Tyrannosaurus
'Pachycephalosaurus
'Mamenchisaurus
'Edmontosaurus
'Deinonychus
'Amargasaurus
'
'BinarySearch for 'Coelophysis':
'Not found. Sorts between: Deinonychus and Amargasaurus.
'
'BinarySearch for 'Tyrannosaurus':
'Found at index 0.
注解
如果 comparer
null
,array
的每个元素都必须实现 IComparable<T> 泛型接口,才能与 array
中所有其他元素进行比较。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
是 array
的 Length。
调用方说明
.NET Framework 4 和早期版本仅使用 Quicksort 算法。 在排序操作引发 IndexOutOfRangeException 异常,并向调用方引发 ArgumentException 异常的情况下,Quicksort 标识无效比较器。 从 .NET Framework 4.5 开始,以前引发 ArgumentException 的排序操作可能不会引发异常,因为插入排序和堆算法不会检测到无效比较器。 在大多数情况下,这适用于小于或等于 16 个元素的数组。
另请参阅
- IComparer<T>
- IComparable<T>
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort<T>(T[], Comparison<T>)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
使用指定的 Comparison<T>对 Array 中的元素进行排序。
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[]
要排序的从零开始的一维 Array。
- comparison
- Comparison<T>
比较元素时要使用的 Comparison<T>。
例外
comparison
的实现在排序过程中导致错误。 例如,将项与自身进行比较时,comparison
可能不会返回 0。
示例
下面的代码示例演示了 Sort(Comparison<T>) 方法重载。
该代码示例为名为 CompareDinosByLength
的字符串定义替代比较方法。 此方法的工作方式如下:首先,比较器会针对null
进行测试,并将 null 引用视为小于非 null。 其次,比较字符串长度,较长的字符串被视为更大。 第三,如果长度相等,则使用普通字符串比较。
创建字符串数组,并填充四个字符串,无特定顺序。 该列表还包括一个空字符串和一个 null 引用。 该列表使用表示 CompareDinosByLength
方法的 Comparison<T> 泛型委托进行排序,并再次显示。
using namespace System;
using namespace System::Collections::Generic;
int CompareDinosByLength(String^ x, String^ y)
{
if (x == nullptr)
{
if (y == nullptr)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == nullptr)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int retval = x->Length.CompareTo(y->Length);
if (retval != 0)
{
// If the strings are not of equal length,
// the longer string is greater.
//
return retval;
}
else
{
// If the strings are of equal length,
// sort them with ordinary string comparison.
//
return x->CompareTo(y);
}
}
}
};
void Display(array<String^>^ arr)
{
Console::WriteLine();
for each(String^ s in arr)
{
if (s == nullptr)
Console::WriteLine("(null)");
else
Console::WriteLine("\"{0}\"", s);
}
};
void main()
{
array<String^>^ dinosaurs = {
"Pachycephalosaurus",
"Amargasaurus",
"",
nullptr,
"Mamenchisaurus",
"Deinonychus" };
Display(dinosaurs);
Console::WriteLine("\nSort with generic Comparison<String^> delegate:");
Array::Sort(dinosaurs,
gcnew Comparison<String^>(CompareDinosByLength));
Display(dinosaurs);
}
/* This code example produces the following output:
"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"
Sort with generic Comparison<String^> delegate:
(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
*/
using System;
using System.Collections.Generic;
public class Example
{
private static int CompareDinosByLength(string x, string y)
{
if (x == null)
{
if (y == null)
{
// If x is null and y is null, they're
// equal.
return 0;
}
else
{
// If x is null and y is not null, y
// is greater.
return -1;
}
}
else
{
// If x is not null...
//
if (y == null)
// ...and y is null, x is greater.
{
return 1;
}
else
{
// ...and y is not null, compare the
// lengths of the two strings.
//
int retval = x.Length.CompareTo(y.Length);
if (retval != 0)
{
// If the strings are not of equal length,
// the longer string is greater.
//
return retval;
}
else
{
// If the strings are of equal length,
// sort them with ordinary string comparison.
//
return x.CompareTo(y);
}
}
}
}
public static void Main()
{
string[] dinosaurs = {
"Pachycephalosaurus",
"Amargasaurus",
"",
null,
"Mamenchisaurus",
"Deinonychus" };
Display(dinosaurs);
Console.WriteLine("\nSort with generic Comparison<string> delegate:");
Array.Sort(dinosaurs, CompareDinosByLength);
Display(dinosaurs);
}
private static void Display(string[] arr)
{
Console.WriteLine();
foreach( string s in arr )
{
if (s == null)
Console.WriteLine("(null)");
else
Console.WriteLine("\"{0}\"", s);
}
}
}
/* This code example produces the following output:
"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"
Sort with generic Comparison<string> delegate:
(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
*/
open System
let compareDinosByLength (x: string) (y: string) =
match x with
// If x is null and y is null, they're equal.
| null when isNull y -> 0
// If x is null and y is not null, y is greater.
| null -> -1
// If x is not null and y is null, x is greater.
| _ when isNull y -> 1
// If x is not null and y is not null, compare the lengths of the two strings.
| _ ->
let retval = x.Length.CompareTo y.Length
if retval <> 0 then
// If the strings are not of equal length, the longer string is greater.
retval
else
// If the strings are of equal length, sort them with ordinary string comparison.
x.CompareTo y
let display arr =
printfn ""
for s in arr do
if isNull s then
printfn "(null)"
else
printfn $"\"{s}\""
let dinosaurs =
[| "Pachycephalosaurus"
"Amargasaurus"
""
null
"Mamenchisaurus"
"Deinonychus" |]
display dinosaurs
printfn "\nSort with generic Comparison<string> delegate:"
Array.Sort(dinosaurs, compareDinosByLength)
display dinosaurs
// This code example produces the following output:
//
// "Pachycephalosaurus"
// "Amargasaurus"
// ""
// (null)
// "Mamenchisaurus"
// "Deinonychus"
//
// Sort with generic Comparison<string> delegate:
//
// (null)
// ""
// "Deinonychus"
// "Amargasaurus"
// "Mamenchisaurus"
// "Pachycephalosaurus"
//
Imports System.Collections.Generic
Public Class Example
Private Shared Function CompareDinosByLength( _
ByVal x As String, ByVal y As String) As Integer
If x Is Nothing Then
If y Is Nothing Then
' If x is Nothing and y is Nothing, they're
' equal.
Return 0
Else
' If x is Nothing and y is not Nothing, y
' is greater.
Return -1
End If
Else
' If x is not Nothing...
'
If y Is Nothing Then
' ...and y is Nothing, x is greater.
Return 1
Else
' ...and y is not Nothing, compare the
' lengths of the two strings.
'
Dim retval As Integer = _
x.Length.CompareTo(y.Length)
If retval <> 0 Then
' If the strings are not of equal length,
' the longer string is greater.
'
Return retval
Else
' If the strings are of equal length,
' sort them with ordinary string comparison.
'
Return x.CompareTo(y)
End If
End If
End If
End Function
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Pachycephalosaurus", _
"Amargasaurus", _
"", _
Nothing, _
"Mamenchisaurus", _
"Deinonychus" }
Display(dinosaurs)
Console.WriteLine(vbLf & "Sort with generic Comparison(Of String) delegate:")
Array.Sort(dinosaurs, AddressOf CompareDinosByLength)
Display(dinosaurs)
End Sub
Private Shared Sub Display(ByVal arr() As String)
Console.WriteLine()
For Each s As String In arr
If s Is Nothing Then
Console.WriteLine("(Nothing)")
Else
Console.WriteLine("""{0}""", s)
End If
Next
End Sub
End Class
' This code example produces the following output:
'
'"Pachycephalosaurus"
'"Amargasaurus"
'""
'(Nothing)
'"Mamenchisaurus"
'"Deinonychus"
'
'Sort with generic Comparison(Of String) delegate:
'
'(Nothing)
'""
'"Deinonychus"
'"Amargasaurus"
'"Mamenchisaurus"
'"Pachycephalosaurus"
注解
如果排序未成功完成,则结果未定义。
此方法使用内省排序(introsort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
是 array
的 Length。
调用方说明
.NET Framework 4 和早期版本仅使用 Quicksort 算法。 在排序操作引发 IndexOutOfRangeException 异常,并向调用方引发 ArgumentException 异常的情况下,Quicksort 标识无效比较器。 从 .NET Framework 4.5 开始,以前引发 ArgumentException 的排序操作可能不会引发异常,因为插入排序和堆算法不会检测到无效比较器。 在大多数情况下,这适用于小于或等于 6 个元素的数组。
另请参阅
- Comparison<T>
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort<T>(T[], Int32, Int32)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
使用 Array每个元素的 IComparable<T> 泛型接口实现对 Array 中元素范围内的元素进行排序。
public:
generic <typename T>
static void Sort(cli::array <T> ^ array, int index, int length);
public static void Sort<T> (T[] array, int index, int length);
static member Sort : 'T[] * int * int -> unit
Public Shared Sub Sort(Of T) (array As T(), index As Integer, length As Integer)
类型参数
- T
数组元素的类型。
参数
- array
- T[]
要排序的从零开始的一维 Array。
- index
- Int32
要排序的范围的起始索引。
- length
- Int32
要排序的范围中的元素数。
例外
array
null
。
index
和 length
未在 array
中指定有效范围。
array
中的一个或多个元素不实现 IComparable<T> 泛型接口。
示例
下面的代码示例演示 Sort<T>(T[], Int32, Int32) 泛型方法重载和用于对数组中的范围进行排序的 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 泛型方法重载。
该代码示例为名为 ReverseCompare
的字符串定义一个替代比较器,该比较器实现 visual Basic 中的 IComparer<string>
(IComparer(Of String)
,在 Visual C++) 泛型接口中 IComparer<String^>
。 比较器调用 CompareTo(String) 方法,反转比较器的顺序,使字符串排序高到低,而不是低到高。
该代码示例创建并显示一组恐龙名称,由三只食草动物组成,后跟三只食肉动物(精确)。
Sort<T>(T[], Int32, Int32) 泛型方法重载用于对数组的最后三个元素进行排序,然后显示该元素。
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 泛型方法重载用于 ReverseCompare
以相反顺序对最后三个元素进行排序。 彻底困惑的恐龙再次显示。
注意
对 Sort<T>(T[], IComparer<T>) 和 BinarySearch<T>(T[], T, IComparer<T>) 泛型方法的调用与其非泛型方法的调用不同,因为 Visual Basic、C# 和C++从第一个参数的类型推断泛型类型参数的类型。 如果使用 Ildasm.exe(IL 反汇编程序) 检查Microsoft中间语言(MSIL),可以看到正在调用泛型方法。
using namespace System;
using namespace System::Collections::Generic;
public ref class ReverseComparer: IComparer<String^>
{
public:
virtual int Compare(String^ x, String^ y)
{
// Compare y and x in reverse order.
return y->CompareTo(x);
}
};
void main()
{
array<String^>^ dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Mamenchisaurus",
"Tarbosaurus",
"Tyrannosaurus",
"Albertasaurus"};
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nSort(dinosaurs, 3, 3)");
Array::Sort(dinosaurs, 3, 3);
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
ReverseComparer^ rc = gcnew ReverseComparer();
Console::WriteLine("\nSort(dinosaurs, 3, 3, rc)");
Array::Sort(dinosaurs, 3, 3, rc);
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus
Sort(dinosaurs, 3, 3)
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus
Sort(dinosaurs, 3, 3, rc)
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
*/
using System;
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Mamenchisaurus",
"Tarbosaurus",
"Tyrannosaurus",
"Albertasaurus"};
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nSort(dinosaurs, 3, 3)");
Array.Sort(dinosaurs, 3, 3);
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
ReverseComparer rc = new ReverseComparer();
Console.WriteLine("\nSort(dinosaurs, 3, 3, rc)");
Array.Sort(dinosaurs, 3, 3, rc);
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
}
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus
Sort(dinosaurs, 3, 3)
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus
Sort(dinosaurs, 3, 3, rc)
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
*/
open System
open System.Collections.Generic
type ReverseComparer() =
interface IComparer<string> with
member _.Compare(x, y) =
y.CompareTo x
let dinosaurs =
[| "Pachycephalosaurus"
"Amargasaurus"
"Mamenchisaurus"
"Tarbosaurus"
"Tyrannosaurus"
"Albertasaurus" |]
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
printfn "\nSort(dinosaurs, 3, 3)"
Array.Sort(dinosaurs, 3, 3)
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
let rc = ReverseComparer()
printfn "\nSort(dinosaurs, 3, 3, rc)"
Array.Sort(dinosaurs, 3, 3, rc)
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
// This code example produces the following output:
//
// Pachycephalosaurus
// Amargasaurus
// Mamenchisaurus
// Tarbosaurus
// Tyrannosaurus
// Albertasaurus
//
// Sort(dinosaurs, 3, 3)
//
// Pachycephalosaurus
// Amargasaurus
// Mamenchisaurus
// Albertasaurus
// Tarbosaurus
// Tyrannosaurus
//
// Sort(dinosaurs, 3, 3, rc)
//
// Pachycephalosaurus
// Amargasaurus
// Mamenchisaurus
// Tyrannosaurus
// Tarbosaurus
// Albertasaurus
Imports System.Collections.Generic
Public Class ReverseComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, _
ByVal y As String) As Integer _
Implements IComparer(Of String).Compare
' Compare y and x in reverse order.
Return y.CompareTo(x)
End Function
End Class
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Pachycephalosaurus", _
"Amargasaurus", _
"Mamenchisaurus", _
"Tarbosaurus", _
"Tyrannosaurus", _
"Albertasaurus" }
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & "Sort(dinosaurs, 3, 3)")
Array.Sort(dinosaurs, 3, 3)
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Dim rc As New ReverseComparer()
Console.WriteLine(vbLf & "Sort(dinosaurs, 3, 3, rc)")
Array.Sort(dinosaurs, 3, 3, rc)
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
End Sub
End Class
' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Tarbosaurus
'Tyrannosaurus
'Albertasaurus
'
'Sort(dinosaurs, 3, 3)
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Albertasaurus
'Tarbosaurus
'Tyrannosaurus
'
'Sort(dinosaurs, 3, 3, rc)
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Tyrannosaurus
'Tarbosaurus
'Albertasaurus
注解
array
中指定元素范围内的每个元素都必须实现 IComparable<T> 泛型接口,才能与 array
中所有其他元素进行比较。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
length
。
另请参阅
- IComparable<T>
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort<T>(T[], Int32, Int32, IComparer<T>)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
使用指定的 IComparer<T> 泛型接口对 Array 中元素范围内的元素进行排序。
public:
generic <typename T>
static void Sort(cli::array <T> ^ array, int index, int length, System::Collections::Generic::IComparer<T> ^ comparer);
public static void Sort<T> (T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer);
public static void Sort<T> (T[] array, int index, int length, System.Collections.Generic.IComparer<T>? comparer);
static member Sort : 'T[] * int * int * System.Collections.Generic.IComparer<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), index As Integer, length As Integer, comparer As IComparer(Of T))
类型参数
- T
数组元素的类型。
参数
- array
- T[]
要排序的从零开始的一维 Array。
- index
- Int32
要排序的范围的起始索引。
- length
- Int32
要排序的范围中的元素数。
- comparer
- IComparer<T>
比较元素时要使用的 IComparer<T> 泛型接口实现,或 null
使用每个元素的 IComparable<T> 泛型接口实现。
例外
array
null
。
index
和 length
未在 array
中指定有效范围。
-或-
comparer
的实现在排序过程中导致错误。 例如,将项与自身进行比较时,comparer
可能不会返回 0。
comparer
null
,array
中的一个或多个元素不实现 IComparable<T> 泛型接口。
示例
下面的代码示例演示 Sort<T>(T[], Int32, Int32) 泛型方法重载和用于对数组中的范围进行排序的 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 泛型方法重载。
该代码示例为名为 ReverseCompare
的字符串定义一个替代比较器,该比较器实现 visual Basic 中的 IComparer<string>
(IComparer(Of String)
,在 Visual C++) 泛型接口中 IComparer<String^>
。 比较器调用 CompareTo(String) 方法,反转比较器的顺序,使字符串排序高到低,而不是低到高。
该代码示例创建并显示一组恐龙名称,由三只食草动物组成,后跟三只食肉动物(精确)。
Sort<T>(T[], Int32, Int32) 泛型方法重载用于对数组的最后三个元素进行排序,然后显示该元素。
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 泛型方法重载用于 ReverseCompare
以相反顺序对最后三个元素进行排序。 彻底困惑的恐龙再次显示。
注意
对 Sort<T>(T[], IComparer<T>) 和 BinarySearch<T>(T[], T, IComparer<T>) 泛型方法的调用与其非泛型方法的调用不同,因为 Visual Basic、C# 和C++从第一个参数的类型推断泛型类型参数的类型。 如果使用 Ildasm.exe(IL 反汇编程序) 检查Microsoft中间语言(MSIL),可以看到正在调用泛型方法。
using namespace System;
using namespace System::Collections::Generic;
public ref class ReverseComparer: IComparer<String^>
{
public:
virtual int Compare(String^ x, String^ y)
{
// Compare y and x in reverse order.
return y->CompareTo(x);
}
};
void main()
{
array<String^>^ dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Mamenchisaurus",
"Tarbosaurus",
"Tyrannosaurus",
"Albertasaurus"};
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
Console::WriteLine("\nSort(dinosaurs, 3, 3)");
Array::Sort(dinosaurs, 3, 3);
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
ReverseComparer^ rc = gcnew ReverseComparer();
Console::WriteLine("\nSort(dinosaurs, 3, 3, rc)");
Array::Sort(dinosaurs, 3, 3, rc);
Console::WriteLine();
for each(String^ dinosaur in dinosaurs)
{
Console::WriteLine(dinosaur);
}
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus
Sort(dinosaurs, 3, 3)
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus
Sort(dinosaurs, 3, 3, rc)
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
*/
using System;
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Mamenchisaurus",
"Tarbosaurus",
"Tyrannosaurus",
"Albertasaurus"};
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nSort(dinosaurs, 3, 3)");
Array.Sort(dinosaurs, 3, 3);
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
ReverseComparer rc = new ReverseComparer();
Console.WriteLine("\nSort(dinosaurs, 3, 3, rc)");
Array.Sort(dinosaurs, 3, 3, rc);
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
}
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tarbosaurus
Tyrannosaurus
Albertasaurus
Sort(dinosaurs, 3, 3)
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Albertasaurus
Tarbosaurus
Tyrannosaurus
Sort(dinosaurs, 3, 3, rc)
Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Tyrannosaurus
Tarbosaurus
Albertasaurus
*/
open System
open System.Collections.Generic
type ReverseComparer() =
interface IComparer<string> with
member _.Compare(x, y) =
y.CompareTo x
let dinosaurs =
[| "Pachycephalosaurus"
"Amargasaurus"
"Mamenchisaurus"
"Tarbosaurus"
"Tyrannosaurus"
"Albertasaurus" |]
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
printfn "\nSort(dinosaurs, 3, 3)"
Array.Sort(dinosaurs, 3, 3)
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
let rc = ReverseComparer()
printfn "\nSort(dinosaurs, 3, 3, rc)"
Array.Sort(dinosaurs, 3, 3, rc)
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
// This code example produces the following output:
//
// Pachycephalosaurus
// Amargasaurus
// Mamenchisaurus
// Tarbosaurus
// Tyrannosaurus
// Albertasaurus
//
// Sort(dinosaurs, 3, 3)
//
// Pachycephalosaurus
// Amargasaurus
// Mamenchisaurus
// Albertasaurus
// Tarbosaurus
// Tyrannosaurus
//
// Sort(dinosaurs, 3, 3, rc)
//
// Pachycephalosaurus
// Amargasaurus
// Mamenchisaurus
// Tyrannosaurus
// Tarbosaurus
// Albertasaurus
Imports System.Collections.Generic
Public Class ReverseComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, _
ByVal y As String) As Integer _
Implements IComparer(Of String).Compare
' Compare y and x in reverse order.
Return y.CompareTo(x)
End Function
End Class
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Pachycephalosaurus", _
"Amargasaurus", _
"Mamenchisaurus", _
"Tarbosaurus", _
"Tyrannosaurus", _
"Albertasaurus" }
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & "Sort(dinosaurs, 3, 3)")
Array.Sort(dinosaurs, 3, 3)
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Dim rc As New ReverseComparer()
Console.WriteLine(vbLf & "Sort(dinosaurs, 3, 3, rc)")
Array.Sort(dinosaurs, 3, 3, rc)
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
End Sub
End Class
' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Tarbosaurus
'Tyrannosaurus
'Albertasaurus
'
'Sort(dinosaurs, 3, 3)
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Albertasaurus
'Tarbosaurus
'Tyrannosaurus
'
'Sort(dinosaurs, 3, 3, rc)
'
'Pachycephalosaurus
'Amargasaurus
'Mamenchisaurus
'Tyrannosaurus
'Tarbosaurus
'Albertasaurus
注解
如果 comparer
null
,array
中指定元素范围内的每个元素都必须实现 IComparable<T> 泛型接口才能与 array
中所有其他元素进行比较。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
length
。
调用方说明
.NET Framework 4 和早期版本仅使用 Quicksort 算法。 在排序操作引发 IndexOutOfRangeException 异常,并向调用方引发 ArgumentException 异常的情况下,Quicksort 标识无效比较器。 从 .NET Framework 4.5 开始,以前引发 ArgumentException 的排序操作可能不会引发异常,因为插入排序和堆算法不会检测到无效比较器。 在大多数情况下,这适用于小于或等于 16 个元素的数组。
另请参阅
- IComparer<T>
- IComparable<T>
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
根据使用指定 IComparer<T> 泛型接口的第一个 Array 中的键对 Array 对象中的元素范围(一个包含键,另一个对象包含相应的项)。
public:
generic <typename TKey, typename TValue>
static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items, int index, int length, System::Collections::Generic::IComparer<TKey> ^ comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items, int index, int length, System.Collections.Generic.IComparer<TKey>? comparer);
static member Sort : 'Key[] * 'Value[] * int * int * System.Collections.Generic.IComparer<'Key> -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue(), index As Integer, length As Integer, comparer As IComparer(Of TKey))
类型参数
- TKey
键数组的元素的类型。
- TValue
项数组的元素的类型。
参数
- keys
- TKey[]
包含要排序的键的从零开始的一维 Array。
- items
- TValue[]
一维从零开始的 Array,其中包含与 keys
中的键对应的项,或 null
仅对 keys
进行排序。
- index
- Int32
要排序的范围的起始索引。
- length
- Int32
要排序的范围中的元素数。
- comparer
- IComparer<TKey>
比较元素时要使用的 IComparer<T> 泛型接口实现,或 null
使用每个元素的 IComparable<T> 泛型接口实现。
例外
keys
null
。
items
不 null
,keys
的下限与 items
的下限不匹配。
-或-
items
不 null
,keys
的长度大于 items
长度。
-或-
index
和 length
未在 keys
Array中指定有效范围。
-或-
items
不 null
,index
和 length
未在 items
Array中指定有效范围。
-或-
comparer
的实现在排序过程中导致错误。 例如,将项与自身进行比较时,comparer
可能不会返回 0。
comparer
null
,keys
Array 中的一个或多个元素不实现 IComparable<T> 泛型接口。
示例
下面的代码示例演示表示键和值的数组对的排序 Sort<TKey,TValue>(TKey[], TValue[])、Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)、Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)和 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 泛型方法重载。
该代码示例为名为 ReverseCompare
的字符串定义一个替代比较器,该比较器实现 visual Basic 中的 IComparer<string>
(IComparer(Of String)
,在 Visual C++) 泛型接口中 IComparer<String^>
。 比较器调用 CompareTo(String) 方法,反转比较器的顺序,使字符串排序高到低,而不是低到高。
该代码示例创建并显示恐龙名称(键)数组和整数数组,表示每只恐龙的最大长度(以米为单位)(值)。 然后,这些数组将排序并显示多次:
Sort<TKey,TValue>(TKey[], TValue[]) 重载用于按第一个数组中的恐龙名称的顺序对两个数组进行排序。
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 重载和
ReverseCompare
实例用于反转配对数组的排序顺序。Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) 重载用于对两个数组的最后三个元素进行排序。
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 重载用于按相反顺序对两个数组的最后三个元素进行排序。
注意
对泛型方法的调用与其非泛型方法的调用不同,因为 Visual Basic、C# 和C++从前两个参数的类型推断泛型类型参数的类型。 如果使用 Ildasm.exe(IL 反汇编程序) 检查Microsoft中间语言(MSIL),可以看到正在调用泛型方法。
using namespace System;
using namespace System::Collections::Generic;
public ref class ReverseComparer: IComparer<String^>
{
public:
virtual int Compare(String^ x, String^ y)
{
// Compare y and x in reverse order.
return y->CompareTo(x);
}
};
void main()
{
array<String^>^ dinosaurs = {
"Seismosaurus",
"Chasmosaurus",
"Coelophysis",
"Mamenchisaurus",
"Caudipteryx",
"Cetiosaurus" };
array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes)");
Array::Sort(dinosaurs, dinosaurSizes);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
ReverseComparer^ rc = gcnew ReverseComparer();
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
Array::Sort(dinosaurs, dinosaurSizes, rc);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
Array::Sort(dinosaurs, dinosaurSizes, 3, 3);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
Array::Sort(dinosaurs, dinosaurSizes, 3, 3, rc);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
}
/* This code example produces the following output:
Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Sort(dinosaurs, dinosaurSizes)
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.
Sort(dinosaurs, dinosaurSizes, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
*/
using System;
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] dinosaurs = {
"Seismosaurus",
"Chasmosaurus",
"Coelophysis",
"Mamenchisaurus",
"Caudipteryx",
"Cetiosaurus" };
int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes)");
Array.Sort(dinosaurs, dinosaurSizes);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
ReverseComparer rc = new ReverseComparer();
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
Array.Sort(dinosaurs, dinosaurSizes, rc);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
Array.Sort(dinosaurs, dinosaurSizes, 3, 3);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
}
}
/* This code example produces the following output:
Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Sort(dinosaurs, dinosaurSizes)
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.
Sort(dinosaurs, dinosaurSizes, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
*/
open System
open System.Collections.Generic
type ReverseComparer() =
interface IComparer<string> with
member _.Compare(x, y) =
y.CompareTo x
let dinosaurs =
[| "Seismosaurus"
"Chasmosaurus"
"Coelophysis"
"Mamenchisaurus"
"Caudipteryx"
"Cetiosaurus" |]
let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes)"
Array.Sort(dinosaurs, dinosaurSizes)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
let rc = ReverseComparer()
printfn "\nSort(dinosaurs, dinosaurSizes, rc)"
Array.Sort(dinosaurs, dinosaurSizes, rc)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
// This code example produces the following output:
//
// Seismosaurus: up to 40 meters long.
// Chasmosaurus: up to 5 meters long.
// Coelophysis: up to 3 meters long.
// Mamenchisaurus: up to 22 meters long.
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
//
// Sort(dinosaurs, dinosaurSizes)
//
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
// Chasmosaurus: up to 5 meters long.
// Coelophysis: up to 3 meters long.
// Mamenchisaurus: up to 22 meters long.
// Seismosaurus: up to 40 meters long.
//
// Sort(dinosaurs, dinosaurSizes, rc)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Chasmosaurus: up to 5 meters long.
// Cetiosaurus: up to 18 meters long.
// Caudipteryx: up to 1 meters long.
//
// Sort(dinosaurs, dinosaurSizes, 3, 3)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
// Chasmosaurus: up to 5 meters long.
//
// Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Chasmosaurus: up to 5 meters long.
// Cetiosaurus: up to 18 meters long.
// Caudipteryx: up to 1 meters long.
Imports System.Collections.Generic
Public Class ReverseComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, _
ByVal y As String) As Integer _
Implements IComparer(Of String).Compare
' Compare y and x in reverse order.
Return y.CompareTo(x)
End Function
End Class
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Seismosaurus", _
"Chasmosaurus", _
"Coelophysis", _
"Mamenchisaurus", _
"Caudipteryx", _
"Cetiosaurus" }
Dim dinosaurSizes() As Integer = { 40, 5, 3, 22, 1, 18 }
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes)")
Array.Sort(dinosaurs, dinosaurSizes)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Dim rc As New ReverseComparer()
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, rc)")
Array.Sort(dinosaurs, dinosaurSizes, rc)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, 3, 3)")
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, 3, 3, rc)")
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
End Sub
End Class
' This code example produces the following output:
'
'Seismosaurus: up to 40 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'
'Sort(dinosaurs, dinosaurSizes)
'
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Seismosaurus: up to 40 meters long.
'
'Sort(dinosaurs, dinosaurSizes, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
注解
keys
Array 中的每个键在 items
Array中都有相应的项。 当键在排序期间重新定位时,items
Array 中的相应项将同样重新定位。 因此,items
Array 按照 keys
Array中相应键的排列方式进行排序。
如果 comparer
null
,则 keys
Array 中指定元素范围内的每个键都必须实现 IComparable<T> 泛型接口才能与其他键进行比较。
如果项数多于键,则可以进行排序,但没有相应键的项将不会进行排序。 如果键数多于项,则无法排序;执行此操作会引发 ArgumentException。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(introsort)算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
length
。
调用方说明
.NET Framework 4 和早期版本仅使用 Quicksort 算法。 在排序操作引发 IndexOutOfRangeException 异常,并向调用方引发 ArgumentException 异常的情况下,Quicksort 标识无效比较器。 从 .NET Framework 4.5 开始,以前引发 ArgumentException 的排序操作可能不会引发异常,因为插入排序和堆算法不会检测到无效比较器。 在大多数情况下,这适用于小于或等于 16 个元素的数组。
另请参阅
- IComparer<T>
- IComparable<T>
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort<TKey,TValue>(TKey[], TValue[])
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
使用每个键的 IComparable<T> 泛型接口实现,根据第一个 Array 中的键对 Array 对象(一个对象包含键,另一个对象包含相应的项)。
public:
generic <typename TKey, typename TValue>
static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items);
static member Sort : 'Key[] * 'Value[] -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue())
类型参数
- TKey
键数组的元素的类型。
- TValue
项数组的元素的类型。
参数
- keys
- TKey[]
包含要排序的键的从零开始的一维 Array。
- items
- TValue[]
一维从零开始的 Array,其中包含与 keys
中的键对应的项,或 null
仅对 keys
进行排序。
例外
keys
null
。
keys
Array 中的一个或多个元素不实现 IComparable<T> 泛型接口。
示例
下面的代码示例演示表示键和值的数组对的排序 Sort<TKey,TValue>(TKey[], TValue[])、Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)、Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)和 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 泛型方法重载。
该代码示例为名为 ReverseCompare
的字符串定义一个替代比较器,该比较器实现 visual Basic 中的 IComparer<string>
(IComparer(Of String)
,在 Visual C++) 泛型接口中 IComparer<String^>
。 比较器调用 CompareTo(String) 方法,反转比较器的顺序,使字符串排序高到低,而不是低到高。
该代码示例创建并显示恐龙名称(键)数组和整数数组,表示每只恐龙的最大长度(以米为单位)(值)。 然后,这些数组将排序并显示多次:
Sort<TKey,TValue>(TKey[], TValue[]) 重载用于按第一个数组中的恐龙名称的顺序对两个数组进行排序。
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 重载和
ReverseCompare
实例用于反转配对数组的排序顺序。Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) 重载用于对两个数组的最后三个元素进行排序。
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 重载用于按相反顺序对两个数组的最后三个元素进行排序。
注意
对泛型方法的调用与其非泛型方法的调用不同,因为 Visual Basic、C# 和C++从前两个参数的类型推断泛型类型参数的类型。 如果使用 Ildasm.exe(IL 反汇编程序) 检查Microsoft中间语言(MSIL),可以看到正在调用泛型方法。
using namespace System;
using namespace System::Collections::Generic;
public ref class ReverseComparer: IComparer<String^>
{
public:
virtual int Compare(String^ x, String^ y)
{
// Compare y and x in reverse order.
return y->CompareTo(x);
}
};
void main()
{
array<String^>^ dinosaurs = {
"Seismosaurus",
"Chasmosaurus",
"Coelophysis",
"Mamenchisaurus",
"Caudipteryx",
"Cetiosaurus" };
array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes)");
Array::Sort(dinosaurs, dinosaurSizes);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
ReverseComparer^ rc = gcnew ReverseComparer();
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
Array::Sort(dinosaurs, dinosaurSizes, rc);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
Array::Sort(dinosaurs, dinosaurSizes, 3, 3);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
Array::Sort(dinosaurs, dinosaurSizes, 3, 3, rc);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
}
/* This code example produces the following output:
Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Sort(dinosaurs, dinosaurSizes)
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.
Sort(dinosaurs, dinosaurSizes, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
*/
using System;
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] dinosaurs = {
"Seismosaurus",
"Chasmosaurus",
"Coelophysis",
"Mamenchisaurus",
"Caudipteryx",
"Cetiosaurus" };
int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes)");
Array.Sort(dinosaurs, dinosaurSizes);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
ReverseComparer rc = new ReverseComparer();
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
Array.Sort(dinosaurs, dinosaurSizes, rc);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
Array.Sort(dinosaurs, dinosaurSizes, 3, 3);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
}
}
/* This code example produces the following output:
Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Sort(dinosaurs, dinosaurSizes)
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.
Sort(dinosaurs, dinosaurSizes, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
*/
open System
open System.Collections.Generic
type ReverseComparer() =
interface IComparer<string> with
member _.Compare(x, y) =
y.CompareTo x
let dinosaurs =
[| "Seismosaurus"
"Chasmosaurus"
"Coelophysis"
"Mamenchisaurus"
"Caudipteryx"
"Cetiosaurus" |]
let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes)"
Array.Sort(dinosaurs, dinosaurSizes)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
let rc = ReverseComparer()
printfn "\nSort(dinosaurs, dinosaurSizes, rc)"
Array.Sort(dinosaurs, dinosaurSizes, rc)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
// This code example produces the following output:
//
// Seismosaurus: up to 40 meters long.
// Chasmosaurus: up to 5 meters long.
// Coelophysis: up to 3 meters long.
// Mamenchisaurus: up to 22 meters long.
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
//
// Sort(dinosaurs, dinosaurSizes)
//
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
// Chasmosaurus: up to 5 meters long.
// Coelophysis: up to 3 meters long.
// Mamenchisaurus: up to 22 meters long.
// Seismosaurus: up to 40 meters long.
//
// Sort(dinosaurs, dinosaurSizes, rc)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Chasmosaurus: up to 5 meters long.
// Cetiosaurus: up to 18 meters long.
// Caudipteryx: up to 1 meters long.
//
// Sort(dinosaurs, dinosaurSizes, 3, 3)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
// Chasmosaurus: up to 5 meters long.
//
// Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Chasmosaurus: up to 5 meters long.
// Cetiosaurus: up to 18 meters long.
// Caudipteryx: up to 1 meters long.
Imports System.Collections.Generic
Public Class ReverseComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, _
ByVal y As String) As Integer _
Implements IComparer(Of String).Compare
' Compare y and x in reverse order.
Return y.CompareTo(x)
End Function
End Class
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Seismosaurus", _
"Chasmosaurus", _
"Coelophysis", _
"Mamenchisaurus", _
"Caudipteryx", _
"Cetiosaurus" }
Dim dinosaurSizes() As Integer = { 40, 5, 3, 22, 1, 18 }
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes)")
Array.Sort(dinosaurs, dinosaurSizes)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Dim rc As New ReverseComparer()
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, rc)")
Array.Sort(dinosaurs, dinosaurSizes, rc)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, 3, 3)")
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, 3, 3, rc)")
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
End Sub
End Class
' This code example produces the following output:
'
'Seismosaurus: up to 40 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'
'Sort(dinosaurs, dinosaurSizes)
'
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Seismosaurus: up to 40 meters long.
'
'Sort(dinosaurs, dinosaurSizes, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
注解
keys
Array 中的每个键在 items
Array中都有相应的项。 当键在排序期间重新定位时,items
Array 中的相应项将同样重新定位。 因此,items
Array 按照 keys
Array中相应键的排列方式进行排序。
keys
Array 中的每个键都必须实现 IComparable<T> 泛型接口才能与其他每个键进行比较。
如果项数多于键,则可以进行排序,但没有相应键的项将不会进行排序。 如果键数多于项,则无法排序;执行此操作会引发 ArgumentException。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
是 array
的 Length。
另请参阅
- IComparable<T>
- BinarySearch
- IDictionary<TKey,TValue>
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
根据使用指定 IComparer<T> 泛型接口的第一个 Array 中的键对 Array 对象(一个对象包含键,另一个对象包含相应的项)。
public:
generic <typename TKey, typename TValue>
static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items, System::Collections::Generic::IComparer<TKey> ^ comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items, System.Collections.Generic.IComparer<TKey>? comparer);
static member Sort : 'Key[] * 'Value[] * System.Collections.Generic.IComparer<'Key> -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue(), comparer As IComparer(Of TKey))
类型参数
- TKey
键数组的元素的类型。
- TValue
项数组的元素的类型。
参数
- keys
- TKey[]
包含要排序的键的从零开始的一维 Array。
- items
- TValue[]
一维从零开始的 Array,其中包含与 keys
中的键对应的项,或 null
仅对 keys
进行排序。
- comparer
- IComparer<TKey>
比较元素时要使用的 IComparer<T> 泛型接口实现,或 null
使用每个元素的 IComparable<T> 泛型接口实现。
例外
keys
null
。
items
不 null
,keys
的下限与 items
的下限不匹配。
-或-
items
不 null
,keys
的长度大于 items
长度。
-或-
comparer
的实现在排序过程中导致错误。 例如,将项与自身进行比较时,comparer
可能不会返回 0。
comparer
null
,keys
Array 中的一个或多个元素不实现 IComparable<T> 泛型接口。
示例
下面的代码示例演示 Sort<TKey,TValue>(TKey[], TValue[])、[]、Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)、Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)和 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 泛型方法重载,用于对表示键和值的数组对进行排序。
该代码示例为名为 ReverseCompare
的字符串定义一个替代比较器,该比较器实现 visual Basic 中的 IComparer<string>
(IComparer(Of String)
,在 Visual C++) 泛型接口中 IComparer<String^>
。 比较器调用 CompareTo(String) 方法,反转比较器的顺序,使字符串排序高到低,而不是低到高。
该代码示例创建并显示恐龙名称(键)数组和整数数组,表示每只恐龙的最大长度(以米为单位)(值)。 然后,这些数组将排序并显示多次:
Sort<TKey,TValue>(TKey[], TValue[]) 重载用于按第一个数组中的恐龙名称的顺序对两个数组进行排序。
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 重载和
ReverseCompare
实例用于反转配对数组的排序顺序。Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) 重载用于对两个数组的最后三个元素进行排序。
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 重载用于按相反顺序对两个数组的最后三个元素进行排序。
注意
对泛型方法的调用与其非泛型方法的调用不同,因为 Visual Basic、C# 和C++从前两个参数的类型推断泛型类型参数的类型。 如果使用 Ildasm.exe(IL 反汇编程序) 检查Microsoft中间语言(MSIL),可以看到正在调用泛型方法。
using namespace System;
using namespace System::Collections::Generic;
public ref class ReverseComparer: IComparer<String^>
{
public:
virtual int Compare(String^ x, String^ y)
{
// Compare y and x in reverse order.
return y->CompareTo(x);
}
};
void main()
{
array<String^>^ dinosaurs = {
"Seismosaurus",
"Chasmosaurus",
"Coelophysis",
"Mamenchisaurus",
"Caudipteryx",
"Cetiosaurus" };
array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes)");
Array::Sort(dinosaurs, dinosaurSizes);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
ReverseComparer^ rc = gcnew ReverseComparer();
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
Array::Sort(dinosaurs, dinosaurSizes, rc);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
Array::Sort(dinosaurs, dinosaurSizes, 3, 3);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
Array::Sort(dinosaurs, dinosaurSizes, 3, 3, rc);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
}
/* This code example produces the following output:
Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Sort(dinosaurs, dinosaurSizes)
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.
Sort(dinosaurs, dinosaurSizes, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
*/
using System;
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] dinosaurs = {
"Seismosaurus",
"Chasmosaurus",
"Coelophysis",
"Mamenchisaurus",
"Caudipteryx",
"Cetiosaurus" };
int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes)");
Array.Sort(dinosaurs, dinosaurSizes);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
ReverseComparer rc = new ReverseComparer();
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
Array.Sort(dinosaurs, dinosaurSizes, rc);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
Array.Sort(dinosaurs, dinosaurSizes, 3, 3);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
}
}
/* This code example produces the following output:
Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Sort(dinosaurs, dinosaurSizes)
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.
Sort(dinosaurs, dinosaurSizes, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
*/
open System
open System.Collections.Generic
type ReverseComparer() =
interface IComparer<string> with
member _.Compare(x, y) =
y.CompareTo x
let dinosaurs =
[| "Seismosaurus"
"Chasmosaurus"
"Coelophysis"
"Mamenchisaurus"
"Caudipteryx"
"Cetiosaurus" |]
let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes)"
Array.Sort(dinosaurs, dinosaurSizes)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
let rc = ReverseComparer()
printfn "\nSort(dinosaurs, dinosaurSizes, rc)"
Array.Sort(dinosaurs, dinosaurSizes, rc)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
// This code example produces the following output:
//
// Seismosaurus: up to 40 meters long.
// Chasmosaurus: up to 5 meters long.
// Coelophysis: up to 3 meters long.
// Mamenchisaurus: up to 22 meters long.
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
//
// Sort(dinosaurs, dinosaurSizes)
//
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
// Chasmosaurus: up to 5 meters long.
// Coelophysis: up to 3 meters long.
// Mamenchisaurus: up to 22 meters long.
// Seismosaurus: up to 40 meters long.
//
// Sort(dinosaurs, dinosaurSizes, rc)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Chasmosaurus: up to 5 meters long.
// Cetiosaurus: up to 18 meters long.
// Caudipteryx: up to 1 meters long.
//
// Sort(dinosaurs, dinosaurSizes, 3, 3)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
// Chasmosaurus: up to 5 meters long.
//
// Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Chasmosaurus: up to 5 meters long.
// Cetiosaurus: up to 18 meters long.
// Caudipteryx: up to 1 meters long.
Imports System.Collections.Generic
Public Class ReverseComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, _
ByVal y As String) As Integer _
Implements IComparer(Of String).Compare
' Compare y and x in reverse order.
Return y.CompareTo(x)
End Function
End Class
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Seismosaurus", _
"Chasmosaurus", _
"Coelophysis", _
"Mamenchisaurus", _
"Caudipteryx", _
"Cetiosaurus" }
Dim dinosaurSizes() As Integer = { 40, 5, 3, 22, 1, 18 }
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes)")
Array.Sort(dinosaurs, dinosaurSizes)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Dim rc As New ReverseComparer()
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, rc)")
Array.Sort(dinosaurs, dinosaurSizes, rc)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, 3, 3)")
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, 3, 3, rc)")
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
End Sub
End Class
' This code example produces the following output:
'
'Seismosaurus: up to 40 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'
'Sort(dinosaurs, dinosaurSizes)
'
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Seismosaurus: up to 40 meters long.
'
'Sort(dinosaurs, dinosaurSizes, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
注解
keys
Array 中的每个键在 items
Array中都有相应的项。 当键在排序期间重新定位时,items
Array 中的相应项将同样重新定位。 因此,items
Array 按照 keys
Array中相应键的排列方式进行排序。
如果 comparer
null
,则 keys
Array 中的每个键都必须实现 IComparable<T> 泛型接口才能与其他每个键进行比较。
如果项数多于键,则可以进行排序,但没有相应键的项将不会进行排序。 如果键数多于项,则无法排序;执行此操作会引发 ArgumentException。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
是 array
的 Length。
调用方说明
.NET Framework 4 和早期版本仅使用 Quicksort 算法。 在排序操作引发 IndexOutOfRangeException 异常,并向调用方引发 ArgumentException 异常的情况下,Quicksort 标识无效比较器。 从 .NET Framework 4.5 开始,以前引发 ArgumentException 的排序操作可能不会引发异常,因为插入排序和堆算法不会检测到无效比较器。 在大多数情况下,这适用于小于或等于 16 个元素的数组。
另请参阅
- IComparer<T>
- IComparable<T>
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作
适用于
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)
- Source:
- Array.cs
- Source:
- Array.cs
- Source:
- Array.cs
根据 Array 每个键的 IComparable<T> 泛型接口实现,对一对 Array 对象中的元素(一个包含键,另一个对象包含相应的项)中的键进行排序。
public:
generic <typename TKey, typename TValue>
static void Sort(cli::array <TKey> ^ keys, cli::array <TValue> ^ items, int index, int length);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items, int index, int length);
public static void Sort<TKey,TValue> (TKey[] keys, TValue[]? items, int index, int length);
static member Sort : 'Key[] * 'Value[] * int * int -> unit
Public Shared Sub Sort(Of TKey, TValue) (keys As TKey(), items As TValue(), index As Integer, length As Integer)
类型参数
- TKey
键数组的元素的类型。
- TValue
项数组的元素的类型。
参数
- keys
- TKey[]
包含要排序的键的从零开始的一维 Array。
- items
- TValue[]
一维从零开始的 Array,其中包含与 keys
中的键对应的项,或 null
仅对 keys
进行排序。
- index
- Int32
要排序的范围的起始索引。
- length
- Int32
要排序的范围中的元素数。
例外
keys
null
。
items
不 null
,keys
的下限与 items
的下限不匹配。
-或-
items
不 null
,keys
的长度大于 items
长度。
-或-
index
和 length
未在 keys
Array中指定有效范围。
-或-
items
不 null
,index
和 length
未在 items
Array中指定有效范围。
keys
Array 中的一个或多个元素不实现 IComparable<T> 泛型接口。
示例
下面的代码示例演示表示键和值的数组对的排序 Sort<TKey,TValue>(TKey[], TValue[])、Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)、Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)和 Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 泛型方法重载。
该代码示例为名为 ReverseCompare
的字符串定义一个替代比较器,该比较器实现 visual Basic 中的 IComparer<string>
(IComparer(Of String)
,在 Visual C++) 泛型接口中 IComparer<String^>
。 比较器调用 CompareTo(String) 方法,反转比较器的顺序,使字符串排序高到低,而不是低到高。
该代码示例创建并显示恐龙名称(键)数组和整数数组,表示每只恐龙的最大长度(以米为单位)(值)。 然后,这些数组将排序并显示多次:
Sort<TKey,TValue>(TKey[], TValue[]) 重载用于按第一个数组中的恐龙名称的顺序对两个数组进行排序。
Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 重载和
ReverseCompare
实例用于反转配对数组的排序顺序。Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32) 重载用于对两个数组的最后三个元素进行排序。
Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) 重载用于按相反顺序对两个数组的最后三个元素进行排序。
注意
对泛型方法的调用与其非泛型方法的调用不同,因为 Visual Basic、C# 和C++从前两个参数的类型推断泛型类型参数的类型。 如果使用 Ildasm.exe(IL 反汇编程序) 检查Microsoft中间语言(MSIL),可以看到正在调用泛型方法。
using namespace System;
using namespace System::Collections::Generic;
public ref class ReverseComparer: IComparer<String^>
{
public:
virtual int Compare(String^ x, String^ y)
{
// Compare y and x in reverse order.
return y->CompareTo(x);
}
};
void main()
{
array<String^>^ dinosaurs = {
"Seismosaurus",
"Chasmosaurus",
"Coelophysis",
"Mamenchisaurus",
"Caudipteryx",
"Cetiosaurus" };
array<int>^ dinosaurSizes = { 40, 5, 3, 22, 1, 18 };
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes)");
Array::Sort(dinosaurs, dinosaurSizes);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
ReverseComparer^ rc = gcnew ReverseComparer();
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
Array::Sort(dinosaurs, dinosaurSizes, rc);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
Array::Sort(dinosaurs, dinosaurSizes, 3, 3);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console::WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
Array::Sort(dinosaurs, dinosaurSizes, 3, 3, rc);
Console::WriteLine();
for (int i = 0; i < dinosaurs->Length; i++)
{
Console::WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
}
/* This code example produces the following output:
Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Sort(dinosaurs, dinosaurSizes)
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.
Sort(dinosaurs, dinosaurSizes, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
*/
using System;
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] dinosaurs = {
"Seismosaurus",
"Chasmosaurus",
"Coelophysis",
"Mamenchisaurus",
"Caudipteryx",
"Cetiosaurus" };
int[] dinosaurSizes = { 40, 5, 3, 22, 1, 18 };
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes)");
Array.Sort(dinosaurs, dinosaurSizes);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
ReverseComparer rc = new ReverseComparer();
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, rc)");
Array.Sort(dinosaurs, dinosaurSizes, rc);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3)");
Array.Sort(dinosaurs, dinosaurSizes, 3, 3);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
Console.WriteLine("\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)");
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc);
Console.WriteLine();
for (int i = 0; i < dinosaurs.Length; i++)
{
Console.WriteLine("{0}: up to {1} meters long.",
dinosaurs[i], dinosaurSizes[i]);
}
}
}
/* This code example produces the following output:
Seismosaurus: up to 40 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Sort(dinosaurs, dinosaurSizes)
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Coelophysis: up to 3 meters long.
Mamenchisaurus: up to 22 meters long.
Seismosaurus: up to 40 meters long.
Sort(dinosaurs, dinosaurSizes, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Caudipteryx: up to 1 meters long.
Cetiosaurus: up to 18 meters long.
Chasmosaurus: up to 5 meters long.
Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Seismosaurus: up to 40 meters long.
Mamenchisaurus: up to 22 meters long.
Coelophysis: up to 3 meters long.
Chasmosaurus: up to 5 meters long.
Cetiosaurus: up to 18 meters long.
Caudipteryx: up to 1 meters long.
*/
open System
open System.Collections.Generic
type ReverseComparer() =
interface IComparer<string> with
member _.Compare(x, y) =
y.CompareTo x
let dinosaurs =
[| "Seismosaurus"
"Chasmosaurus"
"Coelophysis"
"Mamenchisaurus"
"Caudipteryx"
"Cetiosaurus" |]
let dinosaurSizes = [| 40; 5; 3; 22; 1; 18 |]
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes)"
Array.Sort(dinosaurs, dinosaurSizes)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
let rc = ReverseComparer()
printfn "\nSort(dinosaurs, dinosaurSizes, rc)"
Array.Sort(dinosaurs, dinosaurSizes, rc)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
printfn "\nSort(dinosaurs, dinosaurSizes, 3, 3, rc)"
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
printfn ""
for i = 0 to dinosaurs.Length - 1 do
printfn $"{dinosaurs[i]}: up to {dinosaurSizes[i]} meters long."
// This code example produces the following output:
//
// Seismosaurus: up to 40 meters long.
// Chasmosaurus: up to 5 meters long.
// Coelophysis: up to 3 meters long.
// Mamenchisaurus: up to 22 meters long.
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
//
// Sort(dinosaurs, dinosaurSizes)
//
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
// Chasmosaurus: up to 5 meters long.
// Coelophysis: up to 3 meters long.
// Mamenchisaurus: up to 22 meters long.
// Seismosaurus: up to 40 meters long.
//
// Sort(dinosaurs, dinosaurSizes, rc)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Chasmosaurus: up to 5 meters long.
// Cetiosaurus: up to 18 meters long.
// Caudipteryx: up to 1 meters long.
//
// Sort(dinosaurs, dinosaurSizes, 3, 3)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Caudipteryx: up to 1 meters long.
// Cetiosaurus: up to 18 meters long.
// Chasmosaurus: up to 5 meters long.
//
// Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
//
// Seismosaurus: up to 40 meters long.
// Mamenchisaurus: up to 22 meters long.
// Coelophysis: up to 3 meters long.
// Chasmosaurus: up to 5 meters long.
// Cetiosaurus: up to 18 meters long.
// Caudipteryx: up to 1 meters long.
Imports System.Collections.Generic
Public Class ReverseComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, _
ByVal y As String) As Integer _
Implements IComparer(Of String).Compare
' Compare y and x in reverse order.
Return y.CompareTo(x)
End Function
End Class
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Seismosaurus", _
"Chasmosaurus", _
"Coelophysis", _
"Mamenchisaurus", _
"Caudipteryx", _
"Cetiosaurus" }
Dim dinosaurSizes() As Integer = { 40, 5, 3, 22, 1, 18 }
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes)")
Array.Sort(dinosaurs, dinosaurSizes)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Dim rc As New ReverseComparer()
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, rc)")
Array.Sort(dinosaurs, dinosaurSizes, rc)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, 3, 3)")
Array.Sort(dinosaurs, dinosaurSizes, 3, 3)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
Console.WriteLine(vbLf & _
"Sort(dinosaurs, dinosaurSizes, 3, 3, rc)")
Array.Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
Console.WriteLine()
For i As Integer = 0 To dinosaurs.Length - 1
Console.WriteLine("{0}: up to {1} meters long.", _
dinosaurs(i), dinosaurSizes(i))
Next
End Sub
End Class
' This code example produces the following output:
'
'Seismosaurus: up to 40 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'
'Sort(dinosaurs, dinosaurSizes)
'
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'Coelophysis: up to 3 meters long.
'Mamenchisaurus: up to 22 meters long.
'Seismosaurus: up to 40 meters long.
'
'Sort(dinosaurs, dinosaurSizes, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Caudipteryx: up to 1 meters long.
'Cetiosaurus: up to 18 meters long.
'Chasmosaurus: up to 5 meters long.
'
'Sort(dinosaurs, dinosaurSizes, 3, 3, rc)
'
'Seismosaurus: up to 40 meters long.
'Mamenchisaurus: up to 22 meters long.
'Coelophysis: up to 3 meters long.
'Chasmosaurus: up to 5 meters long.
'Cetiosaurus: up to 18 meters long.
'Caudipteryx: up to 1 meters long.
注解
keys
Array 中的每个键在 items
Array中都有相应的项。 当键在排序期间重新定位时,items
Array 中的相应项将同样重新定位。 因此,items
Array 按照 keys
Array中相应键的排列方式进行排序。
keys
Array 中指定元素范围内的每个键都必须实现 IComparable<T> 泛型接口才能与其他每个键进行比较。
如果项数多于键,则可以进行排序,但没有相应键的项将不会进行排序。 如果键数多于项,则无法排序;执行此操作会引发 ArgumentException。
如果排序未成功完成,则结果未定义。
此方法使用内省排序(trosort) 算法,如下所示:
此实现执行不稳定排序;也就是说,如果两个元素相等,则其顺序可能不会保留。 相比之下,稳定的排序会保留相等元素的顺序。
此方法是 O(n
日志 n
)操作,其中 n
length
。
另请参阅
- IComparable<T>
- BinarySearch
- 在数组 中执行 Culture-Insensitive 字符串操作