Array.Sort Metoda

Definicja

Sortuje elementy w tablicy jednowymiarowej.

Przeciążenia

Nazwa Opis
Sort(Array, Array, Int32, Int32, IComparer)

Sortuje zakres elementów w parze jednowymiarowych Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparerelementu .

Sort(Array, Int32, Int32, IComparer)

Sortuje elementy w zakresie elementów w jednowymiarowym Array przy użyciu określonego IComparerelementu .

Sort(Array, Array, Int32, Int32)

Sortuje szereg elementów w parze obiektów jednowymiarowych Array (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu IComparable implementacji każdego klucza.

Sort(Array, Int32, Int32)

Sortuje elementy w zakresie elementów w jednowymiarowym Array przy użyciu IComparable implementacji każdego elementu elementu .Array

Sort(Array, Array, IComparer)

Sortuje parę jednowymiarowych Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparerelementu .

Sort(Array, Array)

Sortuje parę obiektów jednowymiarowych Array (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszej Array kolejności przy użyciu IComparable implementacji każdego klucza.

Sort(Array)

Sortuje elementy w całości jednowymiarowej Array przy użyciu IComparable implementacji każdego elementu obiektu Array.

Sort(Array, IComparer)

Sortuje elementy w jednowymiarowym Array przy użyciu określonego IComparerelementu .

Sort<T>(T[])

Sortuje elementy w całości Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego elementu .Array

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

Sortuje elementy w obiekcie Array przy użyciu określonego IComparer<T> interfejsu ogólnego.

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

Sortuje elementy w obiekcie Array przy użyciu określonego Comparison<T>elementu .

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

Sortuje elementy w zakresie elementów w obiekcie Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego elementu elementu Array.

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

Sortuje elementy w zakresie elementów w obiekcie Array przy użyciu określonego IComparer<T> interfejsu ogólnego.

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

Sortuje zakres elementów w parze Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparer<T> interfejsu ogólnego.

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

Sortuje parę Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszej Array kolejności przy użyciu IComparable<T> implementacji interfejsu ogólnego każdego klucza.

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

Sortuje parę Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparer<T> interfejsu ogólnego.

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

Sortuje szereg elementów w parze Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego klucza.

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

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje zakres elementów w parze jednowymiarowych Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparerelementu .

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)

Parametry

keys
Array

Jednowymiarowy Array , który zawiera klucze do sortowania.

items
Array

Jednowymiarowy Array , który zawiera elementy odpowiadające każdemu z kluczy w obiekcie keysArray.

-lub-

null aby posortować tylko element keysArray.

index
Int32

Indeks początkowy zakresu do sortowania.

length
Int32

Liczba elementów w zakresie do sortowania.

comparer
IComparer

Implementacja IComparer do użycia podczas porównywania elementów.

-lub-

null aby użyć implementacji IComparable każdego elementu.

Wyjątki

Parametr keys ma wartość null.

Element keysArray jest wielowymiarowy.

-lub-

Element itemsArray jest wielowymiarowy.

indexwartość jest mniejsza niż dolna granica .keys

-lub-

Parametr length ma wartość niższą niż zero.

itemsto nie null, a dolna granica keys nie jest zgodna z dolną granicą .items

-lub-

items to nie null, a długość parametru keys jest większa niż długość items.

-lub-

index i length nie należy określać prawidłowego zakresu w obiekcie keysArray.

-lub-

items nie nullma wartości i indexlength nie określa prawidłowego zakresu w obiekcie itemsArray.

-lub-

Implementacja błędu comparer spowodowała błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

comparer to null, a co najmniej jeden element w elemecie keysArray nie implementuje interfejsu IComparable .

Przykłady

Poniższy przykład kodu pokazuje, jak sortować dwie skojarzone tablice, w których pierwsza tablica zawiera klucze, a druga tablica zawiera wartości. Sortowania są wykonywane przy użyciu domyślnego modułu porównania i niestandardowego modułu porównującego, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.

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

Uwagi

Każdy klucz w obiekcie keysma odpowiedni element w elemencie itemsArray.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie itemsArray jest podobnie zmieniany. W związku z tym element itemsArray jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keysArray.

Jeśli comparer element ma nullwartość , każdy klucz w określonym zakresie elementów w keysArray obiekcie musi zaimplementować IComparable interfejs, aby móc porównać każdy inny klucz.

Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie .ArgumentException

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

.NET zawiera wstępnie zdefiniowane implementacje IComparer wymienione w poniższej tabeli.

Implementacja Opis
System.Collections.CaseInsensitiveComparer Porównuje wszystkie dwa obiekty, ale wykonuje porównanie bez uwzględniania wielkości liter ciągów.
Comparer.Default Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania bieżącej kultury.
Comparer.DefaultInvariant Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania niezmiennej kultury.
Comparer<T>.Default Porównuje dwa obiekty typu T przy użyciu domyślnej kolejności sortowania typu.

Można również obsługiwać porównania niestandardowe, podając wystąpienie własnej IComparer implementacji do parametru comparer . W tym przykładzie zdefiniowano niestandardową IComparer implementację, która odwraca domyślną kolejność sortowania i wykonuje porównanie ciągów bez uwzględniania wielkości liter.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n) , gdzie n to length.

Notatki dotyczące wywoływania

Program .NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciły ArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie wstawiania i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.

Zobacz też

Dotyczy

Sort(Array, Int32, Int32, IComparer)

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje elementy w zakresie elementów w jednowymiarowym Array przy użyciu określonego IComparerelementu .

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)

Parametry

array
Array

Jednowymiarowe Array do sortowania.

index
Int32

Indeks początkowy zakresu do sortowania.

length
Int32

Liczba elementów w zakresie do sortowania.

comparer
IComparer

Implementacja IComparer do użycia podczas porównywania elementów.

-lub-

null aby użyć implementacji IComparable każdego elementu.

Wyjątki

Parametr array ma wartość null.

array jest wielowymiarowa.

indexwartość jest mniejsza niż dolna granica .array

-lub-

Parametr length ma wartość niższą niż zero.

indexi length nie należy określać prawidłowego zakresu w elem.array

-lub-

Implementacja błędu comparer spowodowała błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

comparer to null, a co najmniej jeden element w elemecie array nie implementuje interfejsu IComparable .

Przykłady

W poniższym przykładzie kodu pokazano, jak sortować wartości przy Array użyciu domyślnego modułu porównującego i niestandardowego porównania, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.

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

Uwagi

Jeśli comparer element ma nullwartość , każdy element w określonym zakresie elementów w array programie musi zaimplementować IComparable interfejs, aby móc porównać każdy inny element w elemecie array.

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

.NET zawiera wstępnie zdefiniowane implementacje IComparer wymienione w poniższej tabeli.

Implementacja Opis
System.Collections.CaseInsensitiveComparer Porównuje wszystkie dwa obiekty, ale wykonuje porównanie bez uwzględniania wielkości liter ciągów.
Comparer.Default Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania bieżącej kultury.
Comparer.DefaultInvariant Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania niezmiennej kultury.
Comparer<T>.Default Porównuje dwa obiekty typu T przy użyciu domyślnej kolejności sortowania typu.

Można również obsługiwać porównania niestandardowe, podając wystąpienie własnej IComparer implementacji do parametru comparer . W tym przykładzie zdefiniowano klasę, która odwraca domyślną ReverseComparer kolejność sortowania dla wystąpień typu i wykonuje porównanie ciągów bez uwzględniania wielkości liter.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n) , gdzie n to length.

Notatki dotyczące wywoływania

Program .NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciły ArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie wstawiania i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.

Zobacz też

Dotyczy

Sort(Array, Array, Int32, Int32)

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje szereg elementów w parze obiektów jednowymiarowych Array (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu IComparable implementacji każdego klucza.

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)

Parametry

keys
Array

Jednowymiarowy Array , który zawiera klucze do sortowania.

items
Array

Jednowymiarowy Array , który zawiera elementy odpowiadające każdemu z kluczy w obiekcie keysArray.

-lub-

null aby posortować tylko element keysArray.

index
Int32

Indeks początkowy zakresu do sortowania.

length
Int32

Liczba elementów w zakresie do sortowania.

Wyjątki

Parametr keys ma wartość null.

Element keysArray jest wielowymiarowy.

-lub-

Element itemsArray jest wielowymiarowy.

indexwartość jest mniejsza niż dolna granica .keys

-lub-

Parametr length ma wartość niższą niż zero.

items to nie null, a długość parametru keys jest większa niż długość items.

-lub-

index i length nie należy określać prawidłowego zakresu w obiekcie keysArray.

-lub-

items nie nullma wartości i indexlength nie określa prawidłowego zakresu w obiekcie itemsArray.

Co najmniej jeden element w obiekcie keysArray nie implementuje interfejsu IComparable .

Przykłady

Poniższy przykład kodu pokazuje, jak sortować dwie skojarzone tablice, w których pierwsza tablica zawiera klucze, a druga tablica zawiera wartości. Sortowania są wykonywane przy użyciu domyślnego modułu porównania i niestandardowego modułu porównującego, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.

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

Uwagi

Każdy klucz w obiekcie keysma odpowiedni element w elemencie itemsArray.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie itemsArray jest podobnie zmieniany. W związku z tym element itemsArray jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keysArray.

Każdy klucz w określonym zakresie elementów w keysArray obiekcie musi implementować IComparable interfejs, aby móc porównać każdy inny klucz.

Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie .ArgumentException

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n) , gdzie n to length.

Zobacz też

Dotyczy

Sort(Array, Int32, Int32)

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje elementy w zakresie elementów w jednowymiarowym Array przy użyciu IComparable implementacji każdego elementu elementu .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)

Parametry

array
Array

Jednowymiarowe Array do sortowania.

index
Int32

Indeks początkowy zakresu do sortowania.

length
Int32

Liczba elementów w zakresie do sortowania.

Wyjątki

Parametr array ma wartość null.

array jest wielowymiarowa.

indexwartość jest mniejsza niż dolna granica .array

-lub-

Parametr length ma wartość niższą niż zero.

indexi length nie należy określać prawidłowego zakresu w elem.array

Co najmniej jeden element w programie array nie implementuje interfejsu IComparable .

Przykłady

W poniższym przykładzie kodu pokazano, jak sortować wartości przy Array użyciu domyślnego modułu porównującego i niestandardowego porównania, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.

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

Uwagi

Każdy element w określonym zakresie elementów w array systemie musi implementować IComparable interfejs, aby mógł być porównywany z każdym innym elementem w systemie array.

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n) , gdzie n to length.

Zobacz też

Dotyczy

Sort(Array, Array, IComparer)

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje parę jednowymiarowych Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparerelementu .

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)

Parametry

keys
Array

Jednowymiarowy Array , który zawiera klucze do sortowania.

items
Array

Jednowymiarowy Array , który zawiera elementy odpowiadające każdemu z kluczy w obiekcie keysArray.

-lub-

null aby posortować tylko element keysArray.

comparer
IComparer

Implementacja IComparer do użycia podczas porównywania elementów.

-lub-

null aby użyć implementacji IComparable każdego elementu.

Wyjątki

Parametr keys ma wartość null.

Element keysArray jest wielowymiarowy.

-lub-

Element itemsArray jest wielowymiarowy.

items to nie null, a długość parametru keys jest większa niż długość items.

-lub-

Implementacja błędu comparer spowodowała błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

comparer to null, a co najmniej jeden element w elemecie keysArray nie implementuje interfejsu IComparable .

Przykłady

W poniższym przykładzie pokazano, jak sortować dwie skojarzone tablice, w których pierwsza tablica zawiera klucze, a druga tablica zawiera wartości. Sortowania są wykonywane przy użyciu domyślnego modułu porównania i niestandardowego modułu porównującego, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.

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

Uwagi

Każdy klucz w obiekcie keysma odpowiedni element w elemencie itemsArray.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie itemsArray jest podobnie zmieniany. W związku z tym element itemsArray jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keysArray.

Jeśli comparer element ma nullwartość , każdy klucz w elemecie keysArray musi implementować IComparable interfejs, aby móc porównywać z każdym innym kluczem.

Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie .ArgumentException

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

.NET zawiera wstępnie zdefiniowane implementacje IComparer wymienione w poniższej tabeli.

Implementacja Opis
System.Collections.CaseInsensitiveComparer Porównuje wszystkie dwa obiekty, ale wykonuje porównanie bez uwzględniania wielkości liter ciągów.
Comparer.Default Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania bieżącej kultury.
Comparer.DefaultInvariant Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania niezmiennej kultury.
Comparer<T>.Default Porównuje dwa obiekty typu T przy użyciu domyślnej kolejności sortowania typu.

Można również obsługiwać porównania niestandardowe, podając wystąpienie własnej IComparer implementacji do parametru comparer . W tym przykładzie zdefiniowano implementację, która odwraca domyślną IComparer kolejność sortowania i wykonuje porównanie ciągów bez uwzględniania wielkości liter.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n jest Length .keys

Notatki dotyczące wywoływania

Program .NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciły ArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie wstawiania i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.

Zobacz też

Dotyczy

Sort(Array, Array)

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje parę obiektów jednowymiarowych Array (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszej Array kolejności przy użyciu IComparable implementacji każdego klucza.

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)

Parametry

keys
Array

Jednowymiarowy Array , który zawiera klucze do sortowania.

items
Array

Jednowymiarowy Array , który zawiera elementy odpowiadające każdemu z kluczy w obiekcie keysArray.

-lub-

null aby posortować tylko element keysArray.

Wyjątki

Parametr keys ma wartość null.

Element keysArray jest wielowymiarowy.

-lub-

Element itemsArray jest wielowymiarowy.

items to nie null, a długość parametru keys jest większa niż długość items.

Co najmniej jeden element w obiekcie keysArray nie implementuje interfejsu IComparable .

Przykłady

W poniższym przykładzie pokazano, jak sortować dwie skojarzone tablice, w których pierwsza tablica zawiera klucze, a druga tablica zawiera wartości. Sortowania są wykonywane przy użyciu domyślnego modułu porównania i niestandardowego modułu porównującego, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.

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

Uwagi

Każdy klucz w obiekcie keysma odpowiedni element w elemencie itemsArray.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie itemsArray jest podobnie zmieniany. W związku z tym element itemsArray jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keysArray.

Każdy klucz w elemecie keysArray musi implementować IComparable interfejs, aby był w stanie porównać każdy inny klucz.

Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie .ArgumentException

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n jest Length .keys

Zobacz też

Dotyczy

Sort(Array)

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje elementy w całości jednowymiarowej Array przy użyciu IComparable implementacji każdego elementu obiektu 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)

Parametry

array
Array

Jednowymiarowe Array do sortowania.

Wyjątki

Parametr array ma wartość null.

array jest wielowymiarowa.

Co najmniej jeden element w programie array nie implementuje interfejsu IComparable .

Przykłady

W poniższym przykładzie kodu pokazano, jak sortować wartości przy Array użyciu domyślnego modułu porównującego i niestandardowego porównania, który odwraca kolejność sortowania. Należy pamiętać, że wynik może się różnić w zależności od bieżącego CultureInfo.

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

Uwagi

Każdy element array musi zaimplementować IComparable interfejs, aby móc porównywać z każdym innym elementem w elemecie array.

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n jest Length .array

Zobacz też

Dotyczy

Sort(Array, IComparer)

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje elementy w jednowymiarowym Array przy użyciu określonego IComparerelementu .

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)

Parametry

array
Array

Tablica jednowymiarowa do sortowania.

comparer
IComparer

Implementacja do użycia podczas porównywania elementów.

-lub-

null aby użyć implementacji IComparable każdego elementu.

Wyjątki

Parametr array ma wartość null.

array jest wielowymiarowa.

comparer to null, a co najmniej jeden element w elemecie array nie implementuje interfejsu IComparable .

Implementacja błędu comparer spowodowała błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

Przykłady

Poniższy przykład sortuje wartości w tablicy ciągów przy użyciu domyślnego porównania. Definiuje również niestandardową IComparer implementację o nazwie ReverseComparer , która odwraca domyślną kolejność sortowania obiektu podczas porównywania ciągów bez uwzględniania wielkości liter. Należy pamiętać, że dane wyjściowe mogą się różnić w zależności od bieżącej kultury.

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

Uwagi

Jeśli comparer element ma nullwartość , każdy element array musi zaimplementować IComparable interfejs, aby móc porównywać z każdym innym elementem w elemecie array.

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n jest Length .array

.NET zawiera wstępnie zdefiniowane implementacje IComparer wymienione w poniższej tabeli.

Implementacja Opis
System.Collections.CaseInsensitiveComparer Porównuje wszystkie dwa obiekty, ale wykonuje porównanie bez uwzględniania wielkości liter ciągów.
Comparer.Default Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania bieżącej kultury.
Comparer.DefaultInvariant Porównuje wszystkie dwa obiekty przy użyciu konwencji sortowania niezmiennej kultury.
Comparer<T>.Default Porównuje dwa obiekty typu T przy użyciu domyślnej kolejności sortowania typu.

Można również obsługiwać porównania niestandardowe, podając wystąpienie własnej IComparer implementacji do parametru comparer . W tym przykładzie zdefiniowano klasę, która odwraca domyślną ReverseComparer kolejność sortowania dla wystąpień typu i wykonuje porównanie ciągów bez uwzględniania wielkości liter.

Notatki dotyczące wywoływania

Program .NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciły ArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie wstawiania i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.

Zobacz też

Dotyczy

Sort<T>(T[])

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje elementy w całości Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego elementu .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())

Parametry typu

T

Typ elementów tablicy.

Parametry

array
T[]

Jednowymiarowa, zero oparta Array na sortowaniu.

Wyjątki

Parametr array ma wartość null.

Co najmniej jeden element w elemecie array nie implementuje interfejsu IComparable<T> ogólnego.

Przykłady

Poniższy przykład kodu przedstawia Sort<T>(T[]) przeciążenie metody ogólnej i BinarySearch<T>(T[], T) przeciążenie metody ogólnej. Zostanie utworzona tablica ciągów, w żadnej określonej kolejności.

Tablica jest wyświetlana, sortowana i wyświetlana ponownie.

Nuta

Wywołania Sort i BinarySearch metody ogólne nie wyglądają inaczej niż wywołania ich niegenerycznych odpowiedników, ponieważ Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszego argumentu. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka Microsoft pośredniego (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.

Przeciążenie BinarySearch<T>(T[], T) metody ogólnej jest następnie używane do wyszukiwania dwóch ciągów, jeden, który nie znajduje się w tablicy i jeden, który jest. Tablica i zwracana wartość BinarySearch metody są przekazywane do ShowWhere metody ogólnej, która wyświetla wartość indeksu, jeśli ciąg zostanie znaleziony, a w przeciwnym razie elementy, które ciąg wyszukiwania spadnie między, gdyby znajdował się w tablicy. Indeks jest ujemny, jeśli ciąg nie jest n tablicy, więc metoda ShowWhere przyjmuje bitowe uzupełnienie (operator ~ w C#, Xor -1 w Visual Basic) w celu uzyskania indeksu pierwszego elementu na liście, który jest większy niż ciąg wyszukiwania.

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.

Uwagi

Każdy element array musi zaimplementować IComparable<T> interfejs ogólny, aby móc porównywać ze wszystkimi innymi elementami w elemecie array.

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n jest Length .array

Zobacz też

Dotyczy

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

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje elementy w obiekcie Array przy użyciu określonego IComparer<T> interfejsu ogólnego.

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

Parametry typu

T

Typ elementów tablicy.

Parametry

array
T[]

Jednowymiarowa, zero-podstawowa Array do sortowania.

comparer
IComparer<T>

Implementacja IComparer<T> interfejsu ogólnego używana podczas porównywania elementów lub null używania IComparable<T> ogólnej implementacji interfejsu każdego elementu.

Wyjątki

Parametr array ma wartość null.

comparer to null, a co najmniej jeden element w elemecie array nie implementuje interfejsu IComparable<T> ogólnego.

Implementacja błędu comparer spowodowała błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

Przykłady

Poniższy przykład kodu przedstawia Sort<T>(T[], IComparer<T>) przeciążenie metody ogólnej i BinarySearch<T>(T[], T, IComparer<T>) przeciążenie metody ogólnej.

Przykład kodu definiuje alternatywny moduł porównujący ciągi o nazwie ReverseCompare, który implementuje interfejs ogólny IComparer<string> (IComparer(Of String) w Visual Basic). Porównujący wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzanych, tak aby ciągi sortować wysoko do niskich zamiast niskich.

Tablica jest wyświetlana, sortowana i wyświetlana ponownie. Tablice muszą być sortowane w celu użycia BinarySearch metody .

Nuta

Wywołania Sort<T>(T[], IComparer<T>) i BinarySearch<T>(T[], T, IComparer<T>) metody ogólne nie wyglądają inaczej niż wywołania ich niegenerycznych odpowiedników, ponieważ Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszego argumentu. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka Microsoft pośredniego (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.

Przeciążenie BinarySearch<T>(T[], T, IComparer<T>) metody ogólnej jest następnie używane do wyszukiwania dwóch ciągów, jeden, który nie znajduje się w tablicy i jeden, który jest. Tablica i zwracana wartość BinarySearch<T>(T[], T, IComparer<T>) metody są przekazywane do ShowWhere metody ogólnej, która wyświetla wartość indeksu, jeśli ciąg zostanie znaleziony, a w przeciwnym razie elementy, które ciąg wyszukiwania spadnie między, gdyby znajdował się w tablicy. Indeks jest ujemny, jeśli ciąg nie jest n tablicy, więc metoda ShowWhere przyjmuje bitowe uzupełnienie (operator ~ w C#, Xor -1 w Visual Basic) w celu uzyskania indeksu pierwszego elementu na liście, który jest większy niż ciąg wyszukiwania.

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.

Uwagi

Jeśli comparer element ma nullwartość , każdy element array musi zaimplementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym elementem w systemie array.

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n jest Length .array

Notatki dotyczące wywoływania

Program .NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciły ArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie wstawiania i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.

Zobacz też

Dotyczy

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

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje elementy w obiekcie Array przy użyciu określonego Comparison<T>elementu .

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

Parametry typu

T

Typ elementów tablicy.

Parametry

array
T[]

Jednowymiarowa, zero oparta Array na sortowaniu.

comparison
Comparison<T>

Element Comparison<T> do użycia podczas porównywania elementów.

Wyjątki

Parametr array ma wartość null.

-lub-

Parametr comparison ma wartość null.

Implementacja błędu comparison spowodowała błąd podczas sortowania. Na przykład comparison może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

Przykłady

Poniższy przykład kodu przedstawia Sort(Comparison<T>) przeciążenie metody.

Przykład kodu definiuje alternatywną metodę porównania ciągów o nazwie CompareDinosByLength. Ta metoda działa w następujący sposób: Najpierw są sprawdzanenull comparands, a odwołanie o wartości null jest traktowane jako mniejsze niż null. Po drugie, długości ciągów są porównywane, a dłuższy ciąg jest uznawany za większy. Po trzecie, jeśli długości są równe, używane jest zwykłe porównanie ciągów.

Tablica ciągów jest tworzona i wypełniana czterema ciągami w określonej kolejności. Lista zawiera również pusty ciąg i odwołanie o wartości null. Zostanie wyświetlona lista posortowana przy użyciu delegata ogólnego reprezentującego Comparison<T> metodę CompareDinosByLength i wyświetlona ponownie.

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"

Uwagi

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n jest Length .array

Notatki dotyczące wywoływania

Program .NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciły ArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie wstawiania i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 6 elementom.

Zobacz też

Dotyczy

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

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje elementy w zakresie elementów w obiekcie Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego elementu elementu 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)

Parametry typu

T

Typ elementów tablicy.

Parametry

array
T[]

Jednowymiarowa, zero oparta Array na sortowaniu.

index
Int32

Indeks początkowy zakresu do sortowania.

length
Int32

Liczba elementów w zakresie do sortowania.

Wyjątki

Parametr array ma wartość null.

indexwartość jest mniejsza niż dolna granica .array

-lub-

Parametr length ma wartość niższą niż zero.

indexi length nie należy określać prawidłowego zakresu w elem.array

Co najmniej jeden element w elemecie array nie implementuje interfejsu IComparable<T> ogólnego.

Przykłady

Poniższy przykład kodu przedstawia Sort<T>(T[], Int32, Int32) przeciążenie metody ogólnej i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) przeciążenie metody ogólnej do sortowania zakresu w tablicy.

Przykład kodu definiuje alternatywny moduł porównujący dla ciągów o nazwie ReverseCompare, który implementuje interfejs ogólny IComparer<string> (IComparer(Of String) w Visual Basic). Porównujący wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzanych, tak aby ciągi sortować wysoko do niskich zamiast niskich.

Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów składających się z trzech roślin roślinożernych, po których następują trzy mięsożerne (tyrannosauridy, aby być precyzyjne). Przeciążenie Sort<T>(T[], Int32, Int32) metody ogólnej służy do sortowania ostatnich trzech elementów tablicy, które następnie są wyświetlane. Przeciążenie Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) metody ogólnej służy ReverseCompare do sortowania ostatnich trzech elementów w odwrotnej kolejności. Dokładnie zdezorientowane dinozaury są wyświetlane ponownie.

Nuta

Wywołania Sort<T>(T[], IComparer<T>) i BinarySearch<T>(T[], T, IComparer<T>) metody ogólne nie wyglądają inaczej niż wywołania ich niegenerycznych odpowiedników, ponieważ Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszego argumentu. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka Microsoft pośredniego (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.

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

Uwagi

Każdy element w określonym zakresie elementów w array pliku musi implementować IComparable<T> interfejs ogólny, aby móc porównywać ze wszystkimi innymi elementami w elemecie array.

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n) , gdzie n to length.

Zobacz też

Dotyczy

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

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje elementy w zakresie elementów w obiekcie Array przy użyciu określonego IComparer<T> interfejsu ogólnego.

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

Parametry typu

T

Typ elementów tablicy.

Parametry

array
T[]

Jednowymiarowa, zero oparta Array na sortowaniu.

index
Int32

Indeks początkowy zakresu do sortowania.

length
Int32

Liczba elementów w zakresie do sortowania.

comparer
IComparer<T>

Implementacja IComparer<T> interfejsu ogólnego używana podczas porównywania elementów lub null używania IComparable<T> ogólnej implementacji interfejsu każdego elementu.

Wyjątki

Parametr array ma wartość null.

indexwartość jest mniejsza niż dolna granica .array

-lub-

Parametr length ma wartość niższą niż zero.

indexi length nie należy określać prawidłowego zakresu w elem.array

-lub-

Implementacja błędu comparer spowodowała błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

comparer to null, a co najmniej jeden element w elemecie array nie implementuje interfejsu IComparable<T> ogólnego.

Przykłady

Poniższy przykład kodu przedstawia Sort<T>(T[], Int32, Int32) przeciążenie metody ogólnej i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) przeciążenie metody ogólnej do sortowania zakresu w tablicy.

Przykład kodu definiuje alternatywny moduł porównujący dla ciągów o nazwie ReverseCompare, który implementuje interfejs ogólny IComparer<string> (IComparer(Of String) w Visual Basic). Porównujący wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzanych, tak aby ciągi sortować wysoko do niskich zamiast niskich.

Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów składających się z trzech roślin roślinożernych, po których następują trzy mięsożerne (tyrannosauridy, aby być precyzyjne). Przeciążenie Sort<T>(T[], Int32, Int32) metody ogólnej służy do sortowania ostatnich trzech elementów tablicy, które następnie są wyświetlane. Przeciążenie Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) metody ogólnej służy ReverseCompare do sortowania ostatnich trzech elementów w odwrotnej kolejności. Dokładnie zdezorientowane dinozaury są wyświetlane ponownie.

Nuta

Wywołania Sort<T>(T[], IComparer<T>) i BinarySearch<T>(T[], T, IComparer<T>) metody ogólne nie wyglądają inaczej niż wywołania ich niegenerycznych odpowiedników, ponieważ Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszego argumentu. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka Microsoft pośredniego (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.

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

Uwagi

Jeśli comparer element ma nullwartość , każdy element w określonym zakresie elementów w array elemecie musi zaimplementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym elementem w elemecie array.

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n) , gdzie n to length.

Notatki dotyczące wywoływania

Program .NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciły ArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie wstawiania i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.

Zobacz też

Dotyczy

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

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje zakres elementów w parze Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparer<T> interfejsu ogólnego.

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

Parametry typu

TKey

Typ elementów tablicy kluczy.

TValue

Typ elementów tablicy elementów.

Parametry

keys
TKey[]

Jednowymiarowa, zero oparta Array na kluczach do sortowania.

items
TValue[]

Jednowymiarowa, zero oparta Array na elementach, które odpowiadają kluczom w keysobiekcie lub null sortowaniu tylko keys.

index
Int32

Indeks początkowy zakresu do sortowania.

length
Int32

Liczba elementów w zakresie do sortowania.

comparer
IComparer<TKey>

Implementacja IComparer<T> interfejsu ogólnego używana podczas porównywania elementów lub null używania IComparable<T> ogólnej implementacji interfejsu każdego elementu.

Wyjątki

Parametr keys ma wartość null.

indexwartość jest mniejsza niż dolna granica .keys

-lub-

Parametr length ma wartość niższą niż zero.

itemsto nie null, a dolna granica keys nie jest zgodna z dolną granicą .items

-lub-

items to nie null, a długość parametru keys jest większa niż długość items.

-lub-

index i length nie należy określać prawidłowego zakresu w obiekcie keysArray.

-lub-

items nie nullma wartości i indexlength nie określa prawidłowego zakresu w obiekcie itemsArray.

-lub-

Implementacja błędu comparer spowodowała błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

comparer to null, a co najmniej jeden element w obiekcie keysArray nie implementuje interfejsu IComparable<T> ogólnego.

Przykłady

W poniższym przykładzie kodu przedstawiono Sort<TKey,TValue>(TKey[], TValue[])przeciążenia metody , , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ogólnej dla sortowania par tablic reprezentujących klucze i wartości.

Przykład kodu definiuje alternatywny moduł porównujący ciągi o nazwie ReverseCompare, który implementuje interfejs ogólny IComparer<string>(IComparer(Of String) w Visual Basic). Porównujący wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzanych, tak aby ciągi sortować wysoko do niskich zamiast niskich.

Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów (kluczy) oraz tablicę liczb całkowitych reprezentujących maksymalną długość każdego dinozaura w metrach (wartości). Następnie tablice są sortowane i wyświetlane kilka razy:

Nuta

Wywołania metod ogólnych nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszych dwóch argumentów. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka Microsoft pośredniego (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.

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.

Uwagi

Każdy klucz w obiekcie keysma odpowiedni element w elemencie itemsArray.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie itemsArray jest podobnie zmieniany. W związku z tym element itemsArray jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keysArray.

Jeśli comparer element ma nullwartość , każdy klucz w określonym zakresie elementów w obiekcie keysArray musi zaimplementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym kluczem.

Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie .ArgumentException

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n) , gdzie n to length.

Notatki dotyczące wywoływania

Program .NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciły ArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie wstawiania i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.

Zobacz też

Dotyczy

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

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje parę Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszej Array kolejności przy użyciu IComparable<T> implementacji interfejsu ogólnego każdego klucza.

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

Parametry typu

TKey

Typ elementów tablicy kluczy.

TValue

Typ elementów tablicy elementów.

Parametry

keys
TKey[]

Jednowymiarowa, zero oparta Array na kluczach do sortowania.

items
TValue[]

Jednowymiarowa, zero oparta Array na elementach, które odpowiadają kluczom w keysobiekcie lub null sortowaniu tylko keys.

Wyjątki

Parametr keys ma wartość null.

itemsto nie null, a dolna granica keys nie jest zgodna z dolną granicą .items

-lub-

items to nie null, a długość parametru keys jest większa niż długość items.

Co najmniej jeden element w obiekcie keysArray nie implementuje interfejsu IComparable<T> ogólnego.

Przykłady

W poniższym przykładzie kodu przedstawiono Sort<TKey,TValue>(TKey[], TValue[])przeciążenia metody , , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ogólnej dla sortowania par tablic reprezentujących klucze i wartości.

Przykład kodu definiuje alternatywny moduł porównujący dla ciągów o nazwie ReverseCompare, który implementuje interfejs ogólny IComparer<string> (IComparer(Of String) w Visual Basic). Porównujący wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzanych, tak aby ciągi sortować wysoko do niskich zamiast niskich.

Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów (kluczy) oraz tablicę liczb całkowitych reprezentujących maksymalną długość każdego dinozaura w metrach (wartości). Następnie tablice są sortowane i wyświetlane kilka razy:

Nuta

Wywołania metod ogólnych nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszych dwóch argumentów. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka Microsoft pośredniego (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.

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.

Uwagi

Każdy klucz w obiekcie keysma odpowiedni element w elemencie itemsArray.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie itemsArray jest podobnie zmieniany. W związku z tym element itemsArray jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keysArray.

Każdy klucz w elemecie keysArray musi implementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym kluczem.

Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie .ArgumentException

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n jest Length .array

Zobacz też

Dotyczy

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

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje parę Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu określonego IComparer<T> interfejsu ogólnego.

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

Parametry typu

TKey

Typ elementów tablicy kluczy.

TValue

Typ elementów tablicy elementów.

Parametry

keys
TKey[]

Jednowymiarowa, zero oparta Array na kluczach do sortowania.

items
TValue[]

Jednowymiarowa, zero oparta Array na elementach, które odpowiadają kluczom w keysobiekcie lub null sortowaniu tylko keys.

comparer
IComparer<TKey>

Implementacja IComparer<T> interfejsu ogólnego używana podczas porównywania elementów lub null używania IComparable<T> ogólnej implementacji interfejsu każdego elementu.

Wyjątki

Parametr keys ma wartość null.

itemsto nie null, a dolna granica keys nie jest zgodna z dolną granicą .items

-lub-

items to nie null, a długość parametru keys jest większa niż długość items.

-lub-

Implementacja błędu comparer spowodowała błąd podczas sortowania. Na przykład comparer może nie zwracać wartości 0 podczas porównywania elementu z samym sobą.

comparer to null, a co najmniej jeden element w obiekcie keysArray nie implementuje interfejsu IComparable<T> ogólnego.

Przykłady

W poniższym przykładzie kodu pokazano Sort<TKey,TValue>(TKey[], TValue[])przeciążenia metod , [], Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ogólnych dla sortowania par tablic reprezentujących klucze i wartości.

Przykład kodu definiuje alternatywny moduł porównujący dla ciągów o nazwie ReverseCompare, który implementuje interfejs ogólny IComparer<string> (IComparer(Of String) w Visual Basic). Porównujący wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzanych, tak aby ciągi sortować wysoko do niskich zamiast niskich.

Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów (kluczy) oraz tablicę liczb całkowitych reprezentujących maksymalną długość każdego dinozaura w metrach (wartości). Następnie tablice są sortowane i wyświetlane kilka razy:

Nuta

Wywołania metod ogólnych nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszych dwóch argumentów. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka Microsoft pośredniego (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.

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.

Uwagi

Każdy klucz w obiekcie keysma odpowiedni element w elemencie itemsArray.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie itemsArray jest podobnie zmieniany. W związku z tym element itemsArray jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keysArray.

Jeśli comparer element to null, każdy klucz w elemecie keysArray musi implementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym kluczem.

Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie .ArgumentException

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n), gdzie n jest Length .array

Notatki dotyczące wywoływania

Program .NET Framework 4 i starsze wersje używały tylko algorytmu Quicksort. Funkcja Quicksort identyfikuje nieprawidłowe analizatory w niektórych sytuacjach, w których operacja sortowania zgłasza IndexOutOfRangeException wyjątek i zgłasza ArgumentException wyjątek do elementu wywołującego. Począwszy od .NET Framework 4.5, istnieje możliwość, że operacje sortowania, które wcześniej rzuciły ArgumentException, nie zgłaszają wyjątku, ponieważ sortowanie wstawiania i algorytmy stertowania nie wykrywają nieprawidłowego porównania. W większości przypadków dotyczy to tablic o wartości mniejszej lub równej 16 elementom.

Zobacz też

Dotyczy

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

Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs
Źródło:
Array.cs

Sortuje szereg elementów w parze Array obiektów (jeden zawiera klucze, a drugi zawiera odpowiednie elementy) na podstawie kluczy w pierwszym Array przy użyciu IComparable<T> ogólnej implementacji interfejsu każdego klucza.

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)

Parametry typu

TKey

Typ elementów tablicy kluczy.

TValue

Typ elementów tablicy elementów.

Parametry

keys
TKey[]

Jednowymiarowa, zero oparta Array na kluczach do sortowania.

items
TValue[]

Jednowymiarowa, zero oparta Array na elementach, które odpowiadają kluczom w keysobiekcie lub null sortowaniu tylko keys.

index
Int32

Indeks początkowy zakresu do sortowania.

length
Int32

Liczba elementów w zakresie do sortowania.

Wyjątki

Parametr keys ma wartość null.

indexwartość jest mniejsza niż dolna granica .keys

-lub-

Parametr length ma wartość niższą niż zero.

itemsto nie null, a dolna granica keys nie jest zgodna z dolną granicą .items

-lub-

items to nie null, a długość parametru keys jest większa niż długość items.

-lub-

index i length nie należy określać prawidłowego zakresu w obiekcie keysArray.

-lub-

items nie nullma wartości i indexlength nie określa prawidłowego zakresu w obiekcie itemsArray.

Co najmniej jeden element w obiekcie keysArray nie implementuje interfejsu IComparable<T> ogólnego.

Przykłady

W poniższym przykładzie kodu przedstawiono Sort<TKey,TValue>(TKey[], TValue[])przeciążenia metody , , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)i Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ogólnej dla sortowania par tablic reprezentujących klucze i wartości.

Przykład kodu definiuje alternatywny moduł porównujący dla ciągów o nazwie ReverseCompare, który implementuje interfejs ogólny IComparer<string> (IComparer(Of String) w Visual Basic). Porównujący wywołuje metodę CompareTo(String) , odwracając kolejność współzarządzanych, tak aby ciągi sortować wysoko do niskich zamiast niskich.

Przykładowy kod tworzy i wyświetla tablicę nazw dinozaurów (kluczy) oraz tablicę liczb całkowitych reprezentujących maksymalną długość każdego dinozaura w metrach (wartości). Następnie tablice są sortowane i wyświetlane kilka razy:

Nuta

Wywołania metod ogólnych nie wyglądają inaczej niż wywołania do ich niegenerycznych odpowiedników, ponieważ Visual Basic, C# i C++ wywnioskują typ parametru typu ogólnego z typu pierwszych dwóch argumentów. Jeśli używasz Ildasm.exe (dezasembler IL) do zbadania języka Microsoft pośredniego (MSIL), możesz zobaczyć, że wywoływane są metody ogólne.

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.

Uwagi

Każdy klucz w obiekcie keysma odpowiedni element w elemencie itemsArray.Array Gdy klucz jest zmieniany podczas sortowania, odpowiedni element w elemencie itemsArray jest podobnie zmieniany. W związku z tym element itemsArray jest sortowany zgodnie z rozmieszczeniem odpowiednich kluczy w obiekcie keysArray.

Każdy klucz w określonym zakresie elementów w elemecie keysArray musi implementować IComparable<T> interfejs ogólny, aby móc porównywać z każdym innym kluczem.

Można sortować, jeśli istnieje więcej elementów niż klucze, ale elementy, które nie mają odpowiednich kluczy, nie zostaną posortowane. Nie można sortować, jeśli istnieje więcej kluczy niż elementy; wykonanie tej czynności powoduje zgłoszenie .ArgumentException

Jeśli sortowanie nie zostało pomyślnie ukończone, wyniki są niezdefiniowane.

Ta metoda używa algorytmu sortowania introspekcyjnego (introsort) w następujący sposób:

  • Jeśli rozmiar partycji jest mniejszy lub równy 16 elementom, używa algorytmu sortowania wstawiania .

  • Jeśli liczba partycji przekracza 2 * LogN, gdzie N jest zakresem tablicy wejściowej, używa algorytmu heapsort .

  • W przeciwnym razie używa algorytmu Quicksort .

Ta implementacja wykonuje niestabilny sortowanie; oznacza to, że jeśli dwa elementy są równe, ich kolejność może nie zostać zachowana. Natomiast stabilny sortowanie zachowuje kolejność elementów, które są równe.

Ta metoda jest operacją O(n log n) , gdzie n to length.

Zobacz też

Dotyczy