Array.Sort Yöntem

Tanım

Öğeleri tek boyutlu bir dizide sıralar.

Aşırı Yüklemeler

Name Description
Sort(Array, Array, Int32, Int32, IComparer)

Belirtilen öğesini kullanan Arrayilk Array öğedeki anahtarlara göre, bir öğe aralığını bir boyutlu IComparer nesne çiftinde (biri anahtarları, diğeri ise ilgili öğeleri içerir) sıralar.

Sort(Array, Int32, Int32, IComparer)

Belirtilen Arrayöğesini kullanarak tek boyutlu IComparer bir öğe aralığındaki öğeleri sıralar.

Sort(Array, Array, Int32, Int32)

Bir öğe aralığını bir çift tek boyutlu Array nesnede sıralar (biri anahtarları, diğeri de ilgili öğeleri içerir), her anahtarın uygulamasını kullanan Array ilk IComparable anahtarlara göre.

Sort(Array, Int32, Int32)

öğesinin her öğesinin uygulamasını kullanarak Array bir öğe aralığındaki öğeleri IComparabletek boyutlu Array olarak sıralar.

Sort(Array, Array, IComparer)

Belirtilen Arrayöğesini kullanan ilk Array içindeki anahtarlara göre bir boyutlu IComparer nesne çiftini (biri anahtarları, diğeri ise ilgili öğeleri içerir) sıralar.

Sort(Array, Array)

Bir çift tek boyutlu Array nesne (biri anahtarları, diğeri de ilgili öğeleri içerir) her anahtarın uygulamasını kullanan Array ilk IComparable anahtarlara göre sıralar.

Sort(Array)

öğesinin her Arrayöğesinin IComparable uygulamasını kullanarak tek boyutlu Array öğelerin tamamını sıralar.

Sort(Array, IComparer)

Belirtilen Arrayöğesini kullanarak öğeleri tek boyutlu IComparer olarak sıralar.

Sort<T>(T[])

öğesinin her öğesinin Array genel arabirim uygulamasını kullanarak bir bütündeki IComparable<T> öğeleri Arraysıralar.

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

Belirtilen Array genel arabirimi kullanarak içindeki IComparer<T> öğeleri sıralar.

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

belirtilen Arrayöğesini kullanarak içindeki Comparison<T> öğeleri sıralar.

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

içindeki bir öğe aralığındaki öğeleri Array , öğesinin her öğesinin IComparable<T>Arraygenel arabirim uygulamasını kullanarak sıralar.

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

Belirtilen Array genel arabirimi kullanarak içindeki bir IComparer<T> öğe aralığındaki öğeleri sıralar.

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

Belirtilen Array genel arabirimi kullanan ilk Array nesnedeki anahtarlara göre bir nesne çiftindeki IComparer<T> bir öğe aralığını sıralar (biri anahtarları, diğeri de ilgili öğeleri içerir).

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

Bir nesne çiftini Array (biri anahtarları, diğeri de ilgili öğeleri içerir) her anahtarın genel arabirim uygulamasını kullanan Array ilk IComparable<T> anahtarlara göre sıralar.

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

Bir nesne çiftini Array (biri anahtarları, diğeri de ilgili öğeleri içerir) belirtilen Array genel arabirimi kullanan ilk IComparer<T> anahtarlara göre sıralar.

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

Her bir anahtarın genel arabirim uygulamasını kullanan Array ilk Array anahtarlara göre, bir nesne çiftindeki IComparable<T> bir öğe aralığını sıralar (biri anahtarları, diğeri de ilgili öğeleri içerir).

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

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Belirtilen öğesini kullanan Arrayilk Array öğedeki anahtarlara göre, bir öğe aralığını bir boyutlu IComparer nesne çiftinde (biri anahtarları, diğeri ise ilgili öğeleri içerir) sıralar.

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)

Parametreler

keys
Array

Sıralanacak anahtarları içeren tek boyutlu Array .

items
Array

içindeki anahtarların her birine karşılık gelen öğeleri içeren tek boyutluArray.keysArray

-veya-

null yalnızca öğesini sıralamak için keysArray.

index
Int32

Sıralanacak aralığın başlangıç dizini.

length
Int32

Sıralanacak aralıktaki öğelerin sayısı.

comparer
IComparer

IComparer Öğeleri karşılaştırırken kullanılacak uygulama.

-veya-

null her öğenin uygulamasını kullanmak IComparable için.

Özel durumlar

keys, null'e eşittir.

keys Array çok boyutludur.

-veya-

items Array çok boyutludur.

index alt sınırından küçüktür keys.

-veya-

length, sıfırdan küçüktür.

items değeri değildir nullve alt sınırı keys alt sınırıyla itemseşleşmiyor.

-veya-

items değildir nullve uzunluğu değerinden keysitemsbüyüktür.

-veya-

index ve length içinde keysArraygeçerli bir aralık belirtmeyin.

-veya-

items değil nullve indexlength içinde itemsArraygeçerli bir aralık belirtmeyin.

-veya-

uygulaması comparer , sıralama sırasında bir hataya neden oldu. Örneğin, comparer bir öğeyi kendisiyle karşılaştırırken 0 döndürmeyebilir.

comparer , nullve içindeki keysArray bir veya daha fazla öğe arabirimini IComparable uygulamaz.

Örnekler

Aşağıdaki kod örneği, ilk dizinin anahtarları, ikinci dizinin ise değerleri içerdiği ilişkili iki diziyi sıralamayı gösterir. Sıralamalar, varsayılan karşılaştırıcı ve sıralama düzenini tersine çeviren özel bir karşılaştırıcı kullanılarak yapılır. Sonucun geçerli CultureInfoöğesine bağlı olarak değişebileceğini unutmayın.

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

Açıklamalar

içindeki her anahtarın keysArray içinde itemsArraykarşılık gelen bir öğesi vardır. Sıralama sırasında bir anahtar yeniden konumlandırıldığında, içindeki itemsArray ilgili öğe benzer şekilde yeniden konumlandırılır. Bu nedenle, içindeki itemsArray ilgili anahtarların keysArraydüzenlemesine göre sıralanır.

ise comparernull, içindeki belirtilen öğe aralığındaki keysArray her anahtar, diğer tüm anahtarlarla karşılaştırma yapabilmesi için arabirimi uygulamalıdır IComparable .

Anahtarlardan daha fazla öğe varsa sıralayabilirsiniz, ancak karşılık gelen anahtarı olmayan öğeler sıralanmaz. Öğelerden daha fazla anahtar varsa sıralayamazsınız; bunu yapmak bir ArgumentExceptionoluşturur.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

.NET, aşağıdaki tabloda listelenen önceden tanımlanmış IComparer uygulamalarını içerir.

Implementation Açıklama
System.Collections.CaseInsensitiveComparer İki nesneyi karşılaştırır, ancak dizelerin büyük/küçük harfe duyarlı olmayan bir karşılaştırmasını gerçekleştirir.
Comparer.Default Geçerli kültürün sıralama kurallarını kullanarak iki nesneyi karşılaştırır.
Comparer.DefaultInvariant Sabit kültürün sıralama kurallarını kullanarak iki nesneyi karşılaştırır.
Comparer<T>.Default Türün T varsayılan sıralama düzenini kullanarak türün iki nesnesini karşılaştırır.

Ayrıca parametresine kendi IComparer uygulamanızın comparer bir örneğini sağlayarak özel karşılaştırmaları da destekleyebilirsiniz. Örnek bunu varsayılan sıralama düzenini tersine çeviren ve büyük/küçük harfe duyarlı olmayan dize karşılaştırması yapan özel IComparer bir uygulama tanımlayarak yapar.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir; burada n olur length.

Arayanlara Notlar

.NET Framework 4 ve önceki sürümleri yalnızca Quicksort algoritmasını kullanıyordu. Quicksort, sıralama işleminin bir IndexOutOfRangeException özel durum oluşturduğu bazı durumlarda geçersiz karşılaştırıcıları tanımlar ve çağırana bir ArgumentException özel durum oluşturur. .NET Framework 4.5'den başlayarak, daha önce ArgumentException oluşturan sıralama işlemlerinin özel durum oluşturmaması mümkündür çünkü ekleme sıralama ve yığın sıralama algoritmaları geçersiz bir karşılaştırıcı algılamaz. Çoğunlukla bu, 16 öğeden küçük veya buna eşit diziler için geçerlidir.

Ayrıca bkz.

Şunlara uygulanır

Sort(Array, Int32, Int32, IComparer)

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Belirtilen Arrayöğesini kullanarak tek boyutlu IComparer bir öğe aralığındaki öğeleri sıralar.

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)

Parametreler

array
Array

Sıralanacak tek boyutlu Array .

index
Int32

Sıralanacak aralığın başlangıç dizini.

length
Int32

Sıralanacak aralıktaki öğelerin sayısı.

comparer
IComparer

IComparer Öğeleri karşılaştırırken kullanılacak uygulama.

-veya-

null her öğenin uygulamasını kullanmak IComparable için.

Özel durumlar

array, null'e eşittir.

array çok boyutludur.

index alt sınırından küçüktür array.

-veya-

length, sıfırdan küçüktür.

index ve length içinde arraygeçerli bir aralık belirtmeyin.

-veya-

uygulaması comparer , sıralama sırasında bir hataya neden oldu. Örneğin, comparer bir öğeyi kendisiyle karşılaştırırken 0 döndürmeyebilir.

comparer , nullve içindeki array bir veya daha fazla öğe arabirimini uygulamaz IComparable .

Örnekler

Aşağıdaki kod örneği, varsayılan karşılaştırıcı ve sıralama düzenini tersine çeviren özel bir karşılaştırıcı kullanarak içindeki Array değerlerin nasıl sıralanacağını gösterir. Sonucun geçerli CultureInfoöğesine bağlı olarak değişebileceğini unutmayın.

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

Açıklamalar

ise comparernull, içindeki array belirtilen öğe aralığındaki her öğenin içindeki diğer tüm öğelerle IComparablekarşılaştırma yapabilmesi için arabirimini uygulaması array gerekir.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

.NET, aşağıdaki tabloda listelenen önceden tanımlanmış IComparer uygulamalarını içerir.

Implementation Açıklama
System.Collections.CaseInsensitiveComparer İki nesneyi karşılaştırır, ancak dizelerin büyük/küçük harfe duyarlı olmayan bir karşılaştırmasını gerçekleştirir.
Comparer.Default Geçerli kültürün sıralama kurallarını kullanarak iki nesneyi karşılaştırır.
Comparer.DefaultInvariant Sabit kültürün sıralama kurallarını kullanarak iki nesneyi karşılaştırır.
Comparer<T>.Default Türün T varsayılan sıralama düzenini kullanarak türün iki nesnesini karşılaştırır.

Ayrıca parametresine kendi IComparer uygulamanızın comparer bir örneğini sağlayarak özel karşılaştırmaları da destekleyebilirsiniz. Örnek bunu, bir ReverseComparer türün örnekleri için varsayılan sıralama düzenini tersine çeviren ve büyük/küçük harfe duyarlı olmayan dize karşılaştırması yapan bir sınıf tanımlayarak yapar.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir; burada n olur length.

Arayanlara Notlar

.NET Framework 4 ve önceki sürümleri yalnızca Quicksort algoritmasını kullanıyordu. Quicksort, sıralama işleminin bir IndexOutOfRangeException özel durum oluşturduğu bazı durumlarda geçersiz karşılaştırıcıları tanımlar ve çağırana bir ArgumentException özel durum oluşturur. .NET Framework 4.5'den başlayarak, daha önce ArgumentException oluşturan sıralama işlemlerinin özel durum oluşturmaması mümkündür çünkü ekleme sıralama ve yığın sıralama algoritmaları geçersiz bir karşılaştırıcı algılamaz. Çoğunlukla bu, 16 öğeden küçük veya buna eşit diziler için geçerlidir.

Ayrıca bkz.

Şunlara uygulanır

Sort(Array, Array, Int32, Int32)

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Bir öğe aralığını bir çift tek boyutlu Array nesnede sıralar (biri anahtarları, diğeri de ilgili öğeleri içerir), her anahtarın uygulamasını kullanan Array ilk IComparable anahtarlara göre.

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)

Parametreler

keys
Array

Sıralanacak anahtarları içeren tek boyutlu Array .

items
Array

içindeki anahtarların her birine karşılık gelen öğeleri içeren tek boyutluArray.keysArray

-veya-

null yalnızca öğesini sıralamak için keysArray.

index
Int32

Sıralanacak aralığın başlangıç dizini.

length
Int32

Sıralanacak aralıktaki öğelerin sayısı.

Özel durumlar

keys, null'e eşittir.

keys Array çok boyutludur.

-veya-

items Array çok boyutludur.

index alt sınırından küçüktür keys.

-veya-

length, sıfırdan küçüktür.

items değildir nullve uzunluğu değerinden keysitemsbüyüktür.

-veya-

index ve length içinde keysArraygeçerli bir aralık belirtmeyin.

-veya-

items değil nullve indexlength içinde itemsArraygeçerli bir aralık belirtmeyin.

içindeki keysArray bir veya daha fazla öğe arabirimini IComparable uygulamaz.

Örnekler

Aşağıdaki kod örneği, ilk dizinin anahtarları, ikinci dizinin ise değerleri içerdiği ilişkili iki diziyi sıralamayı gösterir. Sıralamalar, varsayılan karşılaştırıcı ve sıralama düzenini tersine çeviren özel bir karşılaştırıcı kullanılarak yapılır. Sonucun geçerli CultureInfoöğesine bağlı olarak değişebileceğini unutmayın.

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

Açıklamalar

içindeki her anahtarın keysArray içinde itemsArraykarşılık gelen bir öğesi vardır. Sıralama sırasında bir anahtar yeniden konumlandırıldığında, içindeki itemsArray ilgili öğe benzer şekilde yeniden konumlandırılır. Bu nedenle, içindeki itemsArray ilgili anahtarların keysArraydüzenlemesine göre sıralanır.

içindeki belirtilen öğe aralığındaki keysArray her anahtar, diğer tüm anahtarlarla karşılaştırma yapabilmesi için arabirimi uygulamalıdır IComparable .

Anahtarlardan daha fazla öğe varsa sıralayabilirsiniz, ancak karşılık gelen anahtarı olmayan öğeler sıralanmaz. Öğelerden daha fazla anahtar varsa sıralayamazsınız; bunu yapmak bir ArgumentExceptionoluşturur.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir; burada n olur length.

Ayrıca bkz.

Şunlara uygulanır

Sort(Array, Int32, Int32)

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

öğesinin her öğesinin uygulamasını kullanarak Array bir öğe aralığındaki öğeleri IComparabletek boyutlu Array olarak sıralar.

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)

Parametreler

array
Array

Sıralanacak tek boyutlu Array .

index
Int32

Sıralanacak aralığın başlangıç dizini.

length
Int32

Sıralanacak aralıktaki öğelerin sayısı.

Özel durumlar

array, null'e eşittir.

array çok boyutludur.

index alt sınırından küçüktür array.

-veya-

length, sıfırdan küçüktür.

index ve length içinde arraygeçerli bir aralık belirtmeyin.

içindeki array bir veya daha fazla öğe arabirimini IComparable uygulamaz.

Örnekler

Aşağıdaki kod örneği, varsayılan karşılaştırıcı ve sıralama düzenini tersine çeviren özel bir karşılaştırıcı kullanarak içindeki Array değerlerin nasıl sıralanacağını gösterir. Sonucun geçerli CultureInfoöğesine bağlı olarak değişebileceğini unutmayın.

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

Açıklamalar

içindeki belirtilen öğe aralığındaki her öğe, array içindeki diğer tüm öğelerle IComparablekarşılaştırma yapabilmesi için arabirimini uygulamalıdırarray.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir; burada n olur length.

Ayrıca bkz.

Şunlara uygulanır

Sort(Array, Array, IComparer)

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Belirtilen Arrayöğesini kullanan ilk Array içindeki anahtarlara göre bir boyutlu IComparer nesne çiftini (biri anahtarları, diğeri ise ilgili öğeleri içerir) sıralar.

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)

Parametreler

keys
Array

Sıralanacak anahtarları içeren tek boyutlu Array .

items
Array

içindeki anahtarların her birine karşılık gelen öğeleri içeren tek boyutluArray.keysArray

-veya-

null yalnızca öğesini sıralamak için keysArray.

comparer
IComparer

IComparer Öğeleri karşılaştırırken kullanılacak uygulama.

-veya-

null her öğenin uygulamasını kullanmak IComparable için.

Özel durumlar

keys, null'e eşittir.

keys Array çok boyutludur.

-veya-

items Array çok boyutludur.

items değildir nullve uzunluğu değerinden keysitemsbüyüktür.

-veya-

uygulaması comparer , sıralama sırasında bir hataya neden oldu. Örneğin, comparer bir öğeyi kendisiyle karşılaştırırken 0 döndürmeyebilir.

comparer , nullve içindeki keysArray bir veya daha fazla öğe arabirimini IComparable uygulamaz.

Örnekler

Aşağıdaki örnekte, ilk dizinin anahtarları, ikinci dizinin ise değerleri içerdiği ilişkili iki diziyi sıralama gösterilmektedir. Sıralamalar, varsayılan karşılaştırıcı ve sıralama düzenini tersine çeviren özel bir karşılaştırıcı kullanılarak yapılır. Sonucun geçerli CultureInfoöğesine bağlı olarak değişebileceğini unutmayın.

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

Açıklamalar

içindeki her anahtarın keysArray içinde itemsArraykarşılık gelen bir öğesi vardır. Sıralama sırasında bir anahtar yeniden konumlandırıldığında, içindeki itemsArray ilgili öğe benzer şekilde yeniden konumlandırılır. Bu nedenle, içindeki itemsArray ilgili anahtarların keysArraydüzenlemesine göre sıralanır.

ise comparernull, içindeki keysArray her anahtar, diğer tüm anahtarlarla karşılaştırma yapabilmesi için arabirimini uygulamalıdır IComparable .

Anahtarlardan daha fazla öğe varsa sıralayabilirsiniz, ancak karşılık gelen anahtarı olmayan öğeler sıralanmaz. Öğelerden daha fazla anahtar varsa sıralayamazsınız; bunu yapmak bir ArgumentExceptionoluşturur.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

.NET, aşağıdaki tabloda listelenen önceden tanımlanmış IComparer uygulamalarını içerir.

Implementation Açıklama
System.Collections.CaseInsensitiveComparer İki nesneyi karşılaştırır, ancak dizelerin büyük/küçük harfe duyarlı olmayan bir karşılaştırmasını gerçekleştirir.
Comparer.Default Geçerli kültürün sıralama kurallarını kullanarak iki nesneyi karşılaştırır.
Comparer.DefaultInvariant Sabit kültürün sıralama kurallarını kullanarak iki nesneyi karşılaştırır.
Comparer<T>.Default Türün T varsayılan sıralama düzenini kullanarak türün iki nesnesini karşılaştırır.

Ayrıca parametresine kendi IComparer uygulamanızın comparer bir örneğini sağlayarak özel karşılaştırmaları da destekleyebilirsiniz. Örnek bunu varsayılan sıralama düzenini tersine çeviren ve büyük/küçük harfe duyarlı olmayan dize karşılaştırması yapan bir IComparer uygulama tanımlayarak yapar.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir ve burada n öğesinin Length değeridir keys.

Arayanlara Notlar

.NET Framework 4 ve önceki sürümleri yalnızca Quicksort algoritmasını kullanıyordu. Quicksort, sıralama işleminin bir IndexOutOfRangeException özel durum oluşturduğu bazı durumlarda geçersiz karşılaştırıcıları tanımlar ve çağırana bir ArgumentException özel durum oluşturur. .NET Framework 4.5'den başlayarak, daha önce ArgumentException oluşturan sıralama işlemlerinin özel durum oluşturmaması mümkündür çünkü ekleme sıralama ve yığın sıralama algoritmaları geçersiz bir karşılaştırıcı algılamaz. Çoğunlukla bu, 16 öğeden küçük veya buna eşit diziler için geçerlidir.

Ayrıca bkz.

Şunlara uygulanır

Sort(Array, Array)

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Bir çift tek boyutlu Array nesne (biri anahtarları, diğeri de ilgili öğeleri içerir) her anahtarın uygulamasını kullanan Array ilk IComparable anahtarlara göre sıralar.

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)

Parametreler

keys
Array

Sıralanacak anahtarları içeren tek boyutlu Array .

items
Array

içindeki anahtarların her birine karşılık gelen öğeleri içeren tek boyutluArray.keysArray

-veya-

null yalnızca öğesini sıralamak için keysArray.

Özel durumlar

keys, null'e eşittir.

keys Array çok boyutludur.

-veya-

items Array çok boyutludur.

items değildir nullve uzunluğu değerinden keysitemsbüyüktür.

içindeki keysArray bir veya daha fazla öğe arabirimini IComparable uygulamaz.

Örnekler

Aşağıdaki örnekte, ilk dizinin anahtarları, ikinci dizinin ise değerleri içerdiği ilişkili iki diziyi sıralama gösterilmektedir. Sıralamalar, varsayılan karşılaştırıcı ve sıralama düzenini tersine çeviren özel bir karşılaştırıcı kullanılarak yapılır. Sonucun geçerli CultureInfoöğesine bağlı olarak değişebileceğini unutmayın.

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

Açıklamalar

içindeki her anahtarın keysArray içinde itemsArraykarşılık gelen bir öğesi vardır. Sıralama sırasında bir anahtar yeniden konumlandırıldığında, içindeki itemsArray ilgili öğe benzer şekilde yeniden konumlandırılır. Bu nedenle, içindeki itemsArray ilgili anahtarların keysArraydüzenlemesine göre sıralanır.

içindeki keysArray her anahtar, diğer tüm anahtarlarla karşılaştırma yapabilmesi için arabirimini uygulamalıdır IComparable .

Anahtarlardan daha fazla öğe varsa sıralayabilirsiniz, ancak karşılık gelen anahtarı olmayan öğeler sıralanmaz. Öğelerden daha fazla anahtar varsa sıralayamazsınız; bunu yapmak bir ArgumentExceptionoluşturur.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir ve burada n öğesinin Length değeridir keys.

Ayrıca bkz.

Şunlara uygulanır

Sort(Array)

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

öğesinin her Arrayöğesinin IComparable uygulamasını kullanarak tek boyutlu Array öğelerin tamamını sıralar.

public:
 static void Sort(Array ^ array);
public static void Sort(Array array);
static member Sort : Array -> unit
Public Shared Sub Sort (array As Array)

Parametreler

array
Array

Sıralanacak tek boyutlu Array .

Özel durumlar

array, null'e eşittir.

array çok boyutludur.

içindeki array bir veya daha fazla öğe arabirimini IComparable uygulamaz.

Örnekler

Aşağıdaki kod örneği, varsayılan karşılaştırıcı ve sıralama düzenini tersine çeviren özel bir karşılaştırıcı kullanarak içindeki Array değerlerin nasıl sıralanacağını gösterir. Sonucun geçerli CultureInfoöğesine bağlı olarak değişebileceğini unutmayın.

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

Açıklamalar

öğesinin array her öğesi, IComparable içindeki arraydiğer tüm öğelerle karşılaştırma yapabilmesi için arabirimini uygulamalıdır.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir ve burada n öğesinin Length değeridir array.

Ayrıca bkz.

Şunlara uygulanır

Sort(Array, IComparer)

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Belirtilen Arrayöğesini kullanarak öğeleri tek boyutlu IComparer olarak sıralar.

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)

Parametreler

array
Array

Sıralanacak tek boyutlu dizi.

comparer
IComparer

Öğeleri karşılaştırırken kullanılacak uygulama.

-veya-

null her öğenin uygulamasını kullanmak IComparable için.

Özel durumlar

array, null'e eşittir.

array çok boyutludur.

comparer , nullve içindeki array bir veya daha fazla öğe arabirimini uygulamaz IComparable .

uygulaması comparer , sıralama sırasında bir hataya neden oldu. Örneğin, comparer bir öğeyi kendisiyle karşılaştırırken 0 döndürmeyebilir.

Örnekler

Aşağıdaki örnek, bir dize dizisindeki değerleri varsayılan karşılaştırıcıyı kullanarak sıralar. Ayrıca büyük/küçük harfe duyarlı olmayan bir dize karşılaştırması gerçekleştirirken nesnenin varsayılan sıralama düzenini tersine çeviren adlı IComparer özel ReverseComparer bir uygulama tanımlar. Çıkışın geçerli kültüre bağlı olarak değişebileceğini unutmayın.

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

Açıklamalar

ise comparernull, her öğesinin arrayIComparable içindeki diğer tüm öğelerle arraykarşılaştırma yapabilmesi için arabirimini uygulaması gerekir.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir ve burada n öğesinin Length değeridir array.

.NET, aşağıdaki tabloda listelenen önceden tanımlanmış IComparer uygulamalarını içerir.

Implementation Açıklama
System.Collections.CaseInsensitiveComparer İki nesneyi karşılaştırır, ancak dizelerin büyük/küçük harfe duyarlı olmayan bir karşılaştırmasını gerçekleştirir.
Comparer.Default Geçerli kültürün sıralama kurallarını kullanarak iki nesneyi karşılaştırır.
Comparer.DefaultInvariant Sabit kültürün sıralama kurallarını kullanarak iki nesneyi karşılaştırır.
Comparer<T>.Default Türün T varsayılan sıralama düzenini kullanarak türün iki nesnesini karşılaştırır.

Ayrıca parametresine kendi IComparer uygulamanızın comparer bir örneğini sağlayarak özel karşılaştırmaları da destekleyebilirsiniz. Örnek bunu, bir ReverseComparer türün örnekleri için varsayılan sıralama düzenini tersine çeviren ve büyük/küçük harfe duyarlı olmayan dize karşılaştırması yapan bir sınıf tanımlayarak yapar.

Arayanlara Notlar

.NET Framework 4 ve önceki sürümleri yalnızca Quicksort algoritmasını kullanıyordu. Quicksort, sıralama işleminin bir IndexOutOfRangeException özel durum oluşturduğu bazı durumlarda geçersiz karşılaştırıcıları tanımlar ve çağırana bir ArgumentException özel durum oluşturur. .NET Framework 4.5'den başlayarak, daha önce ArgumentException oluşturan sıralama işlemlerinin özel durum oluşturmaması mümkündür çünkü ekleme sıralama ve yığın sıralama algoritmaları geçersiz bir karşılaştırıcı algılamaz. Çoğunlukla bu, 16 öğeden küçük veya buna eşit diziler için geçerlidir.

Ayrıca bkz.

Şunlara uygulanır

Sort<T>(T[])

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

öğesinin her öğesinin Array genel arabirim uygulamasını kullanarak bir bütündeki IComparable<T> öğeleri Arraysıralar.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array);
public static void Sort<T>(T[] array);
static member Sort : 'T[] -> unit
Public Shared Sub Sort(Of T) (array As T())

Tür Parametreleri

T

Dizinin öğelerinin türü.

Parametreler

array
T[]

Sıralama için tek boyutlu, sıfır tabanlı Array .

Özel durumlar

array, null'e eşittir.

içindeki array bir veya daha fazla öğe genel arabirimi uygulamaz IComparable<T> .

Örnekler

Aşağıdaki kod örneği, genel yöntem aşırı yüklemesini Sort<T>(T[]) ve genel yöntem aşırı yüklemesini BinarySearch<T>(T[], T) gösterir. Belirli bir sırada olmayan bir dize dizisi oluşturulur.

Dizi görüntülenir, sıralanır ve yeniden görüntülenir.

Note

Sort ve BinarySearch genel yöntemlerine yapılan çağrılar, Visual Basic, C# ve C++ genel tür parametresinin türünü ilk bağımsız değişkenin türünden çıkardığından, genel olmayan karşılıklarına yapılan çağrılardan farklı görünmemektedir. Microsoft ara dili (MSIL) incelemek için Ildasm.exe (IL Disassembler) kullanırsanız, genel yöntemlerin çağrıldığını görebilirsiniz.

Genel BinarySearch<T>(T[], T) yöntem aşırı yüklemesi daha sonra biri dizide olmayan, diğeri de dizide olmayan iki dizeyi aramak için kullanılır. Dizi ve yönteminin BinarySearch dönüş değeri, dize bulunursa dizin değerini görüntüleyen genel yönteme ShowWhere geçirilir ve aksi takdirde, arama dizesi dizide yer alırsa arasında kalan öğeler görüntülenir. Dize dizide n değilse dizin negatif olur, bu nedenle ShowWhere yöntemi, listedeki arama dizesinden daha büyük olan listedeki ilk öğenin dizinini almak için bit düzeyinde tamamlayıcıyı (C#'daki ~ işleci, Visual Basic Xor -1) alır.

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.

Açıklamalar

öğesinin array her öğesi, IComparable<T> içindeki arraydiğer tüm öğelerle karşılaştırma yapabilmesi için genel arabirimi uygulamalıdır.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir ve burada n öğesinin Length değeridir array.

Ayrıca bkz.

Şunlara uygulanır

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

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Belirtilen Array genel arabirimi kullanarak içindeki IComparer<T> öğeleri sıralar.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array, System::Collections::Generic::IComparer<T> ^ comparer);
public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer);
public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T>? comparer);
static member Sort : 'T[] * System.Collections.Generic.IComparer<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), comparer As IComparer(Of T))

Tür Parametreleri

T

Dizinin öğelerinin türü.

Parametreler

array
T[]

Sıralanacak tek boyutlu, sıfır tabanlı Array .

comparer
IComparer<T>

Öğeleri IComparer<T> karşılaştırırken kullanılacak genel arabirim uygulaması veya null her öğenin genel arabirim uygulamasını kullanmak IComparable<T> .

Özel durumlar

array, null'e eşittir.

comparer ve nulliçindeki array bir veya daha fazla öğe genel arabirimi uygulamaz IComparable<T> .

uygulaması comparer , sıralama sırasında bir hataya neden oldu. Örneğin, comparer bir öğeyi kendisiyle karşılaştırırken 0 döndürmeyebilir.

Örnekler

Aşağıdaki kod örneği, genel yöntem aşırı yüklemesini Sort<T>(T[], IComparer<T>) ve genel yöntem aşırı yüklemesini BinarySearch<T>(T[], T, IComparer<T>) gösterir.

Kod örneği, ReverseCompare (Visual Basic'da IComparer<string>) genel arabirimini uygulayan IComparer(Of String) adlı dizeler için alternatif bir karşılaştırıcı tanımlar. Karşılaştırıcı yöntemini çağırır ve dizelerin düşük-yüksek yerine yüksek-düşük sıralanması için karşılaştırıcıların sırasını tersine çevirme CompareTo(String) .

Dizi görüntülenir, sıralanır ve yeniden görüntülenir. Yönteminin kullanılabilmesi BinarySearch için dizilerin sıralanması gerekir.

Note

Sort<T>(T[], IComparer<T>) ve BinarySearch<T>(T[], T, IComparer<T>) genel yöntemlerine yapılan çağrılar, Visual Basic, C# ve C++ genel tür parametresinin türünü ilk bağımsız değişkenin türünden çıkardığından, genel olmayan karşılıklarına yapılan çağrılardan farklı görünmemektedir. Microsoft ara dili (MSIL) incelemek için Ildasm.exe (IL Disassembler) kullanırsanız, genel yöntemlerin çağrıldığını görebilirsiniz.

Genel BinarySearch<T>(T[], T, IComparer<T>) yöntem aşırı yüklemesi daha sonra biri dizide olmayan, diğeri de dizide olmayan iki dizeyi aramak için kullanılır. Dizi ve yönteminin BinarySearch<T>(T[], T, IComparer<T>) dönüş değeri, dize bulunursa dizin değerini görüntüleyen genel yönteme ShowWhere geçirilir ve aksi takdirde, arama dizesi dizide yer alırsa arasında kalan öğeler görüntülenir. Dize dizide n değilse dizin negatif olur, bu nedenle ShowWhere yöntemi, listedeki arama dizesinden daha büyük olan listedeki ilk öğenin dizinini almak için bit düzeyinde tamamlayıcıyı (C#'daki ~ işleci, Visual Basic Xor -1) alır.

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.

Açıklamalar

ise comparernull, öğesinin array her öğesi içindeki IComparable<T> diğer tüm öğelerle arraykarşılaştırma yapabilmesi için genel arabirimi uygulamalıdır.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir ve burada n öğesinin Length değeridir array.

Arayanlara Notlar

.NET Framework 4 ve önceki sürümleri yalnızca Quicksort algoritmasını kullanıyordu. Quicksort, sıralama işleminin bir IndexOutOfRangeException özel durum oluşturduğu bazı durumlarda geçersiz karşılaştırıcıları tanımlar ve çağırana bir ArgumentException özel durum oluşturur. .NET Framework 4.5'den başlayarak, daha önce ArgumentException oluşturan sıralama işlemlerinin özel durum oluşturmaması mümkündür çünkü ekleme sıralama ve yığın sıralama algoritmaları geçersiz bir karşılaştırıcı algılamaz. Çoğunlukla bu, 16 öğeden küçük veya buna eşit diziler için geçerlidir.

Ayrıca bkz.

Şunlara uygulanır

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

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

belirtilen Arrayöğesini kullanarak içindeki Comparison<T> öğeleri sıralar.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array, Comparison<T> ^ comparison);
public static void Sort<T>(T[] array, Comparison<T> comparison);
static member Sort : 'T[] * Comparison<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), comparison As Comparison(Of T))

Tür Parametreleri

T

Dizinin öğelerinin türü.

Parametreler

array
T[]

Sıralama için tek boyutlu, sıfır tabanlı Array .

comparison
Comparison<T>

Comparison<T> öğeleri karşılaştırırken kullanılacak.

Özel durumlar

array, null'e eşittir.

-veya-

comparison, null'e eşittir.

uygulaması comparison , sıralama sırasında bir hataya neden oldu. Örneğin, comparison bir öğeyi kendisiyle karşılaştırırken 0 döndürmeyebilir.

Örnekler

Aşağıdaki kod örneği yöntem aşırı yüklemesini Sort(Comparison<T>) gösterir.

Kod örneği, dizeler için adlı CompareDinosByLengthalternatif bir karşılaştırma yöntemi tanımlar. Bu yöntem şu şekilde çalışır: İlk olarak, karşılaştırmalar içinnull test edilir ve null başvuru null olmayan bir başvurudan küçük olarak kabul edilir. İkincisi, dize uzunlukları karşılaştırılır ve uzun dize daha büyük olarak kabul edilir. Üçüncüsü, uzunluklar eşitse, sıradan dize karşılaştırması kullanılır.

Dize dizisi oluşturulur ve belirli bir sırada olmayan dört dizeyle doldurulur. Listede boş bir dize ve null başvuru da bulunur. Liste görüntülenir, yöntemi temsil eden Comparison<T> genel bir CompareDinosByLength temsilci kullanılarak sıralanır ve yeniden görüntülenir.

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"

Açıklamalar

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntemde aşağıdaki gibi iç gözlem sıralama (introsort) algoritması kullanılır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir ve burada n öğesinin Length değeridir array.

Arayanlara Notlar

.NET Framework 4 ve önceki sürümleri yalnızca Quicksort algoritmasını kullanıyordu. Quicksort, sıralama işleminin bir IndexOutOfRangeException özel durum oluşturduğu bazı durumlarda geçersiz karşılaştırıcıları tanımlar ve çağırana bir ArgumentException özel durum oluşturur. .NET Framework 4.5'den başlayarak, daha önce ArgumentException oluşturan sıralama işlemlerinin özel durum oluşturmaması mümkündür çünkü ekleme sıralama ve yığın sıralama algoritmaları geçersiz bir karşılaştırıcı algılamaz. Çoğunlukla bu, 6 öğeden küçük veya buna eşit diziler için geçerlidir.

Ayrıca bkz.

Şunlara uygulanır

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

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

içindeki bir öğe aralığındaki öğeleri Array , öğesinin her öğesinin IComparable<T>Arraygenel arabirim uygulamasını kullanarak sıralar.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array, int index, int length);
public static void Sort<T>(T[] array, int index, int length);
static member Sort : 'T[] * int * int -> unit
Public Shared Sub Sort(Of T) (array As T(), index As Integer, length As Integer)

Tür Parametreleri

T

Dizinin öğelerinin türü.

Parametreler

array
T[]

Sıralama için tek boyutlu, sıfır tabanlı Array .

index
Int32

Sıralanacak aralığın başlangıç dizini.

length
Int32

Sıralanacak aralıktaki öğelerin sayısı.

Özel durumlar

array, null'e eşittir.

index alt sınırından küçüktür array.

-veya-

length, sıfırdan küçüktür.

index ve length içinde arraygeçerli bir aralık belirtmeyin.

içindeki array bir veya daha fazla öğe genel arabirimi uygulamaz IComparable<T> .

Örnekler

Aşağıdaki kod örneği, bir dizideki Sort<T>(T[], Int32, Int32) bir aralığı sıralamak için genel yöntem aşırı yüklemesini Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ve genel yöntem aşırı yüklemesini gösterir.

Kod örneği, ReverseCompare (Visual Basic'da IComparer<string>) genel arabirimini uygulayan IComparer(Of String) adlı dizeler için alternatif bir karşılaştırıcı tanımlar. Karşılaştırıcı yöntemini çağırır ve dizelerin düşük-yüksek yerine yüksek-düşük sıralanması için karşılaştırıcıların sırasını tersine çevirme CompareTo(String) .

Kod örneği, üç otçul ve ardından üç etoburdan oluşan bir dinozor adları dizisi oluşturur ve görüntüler (kesin olarak tyrannosaurids). Genel Sort<T>(T[], Int32, Int32) yöntem aşırı yüklemesi, dizinin son üç öğesini sıralamak için kullanılır ve daha sonra görüntülenir. Genel Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) yöntem aşırı yüklemesi, son üç öğeyi ters sırada sıralamak için ile ReverseCompare birlikte kullanılır. Kafaları iyice karışmış dinozorlar tekrar görüntüleniyor.

Note

Sort<T>(T[], IComparer<T>) ve BinarySearch<T>(T[], T, IComparer<T>) genel yöntemlerine yapılan çağrılar, Visual Basic, C# ve C++ genel tür parametresinin türünü ilk bağımsız değişkenin türünden çıkardığından, genel olmayan karşılıklarına yapılan çağrılardan farklı görünmemektedir. Microsoft ara dili (MSIL) incelemek için Ildasm.exe (IL Disassembler) kullanırsanız, genel yöntemlerin çağrıldığını görebilirsiniz.

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

Açıklamalar

içindeki array belirtilen öğe aralığındaki her öğenin içindeki diğer tüm öğelerle IComparable<T>karşılaştırma yapabilmesi için genel arabirimi uygulaması array gerekir.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir; burada n olur length.

Ayrıca bkz.

Şunlara uygulanır

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

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Belirtilen Array genel arabirimi kullanarak içindeki bir IComparer<T> öğe aralığındaki öğeleri sıralar.

public:
generic <typename T>
 static void Sort(cli::array <T> ^ array, int index, int length, System::Collections::Generic::IComparer<T> ^ comparer);
public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer);
public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T>? comparer);
static member Sort : 'T[] * int * int * System.Collections.Generic.IComparer<'T> -> unit
Public Shared Sub Sort(Of T) (array As T(), index As Integer, length As Integer, comparer As IComparer(Of T))

Tür Parametreleri

T

Dizinin öğelerinin türü.

Parametreler

array
T[]

Sıralama için tek boyutlu, sıfır tabanlı Array .

index
Int32

Sıralanacak aralığın başlangıç dizini.

length
Int32

Sıralanacak aralıktaki öğelerin sayısı.

comparer
IComparer<T>

Öğeleri IComparer<T> karşılaştırırken kullanılacak genel arabirim uygulaması veya null her öğenin genel arabirim uygulamasını kullanmak IComparable<T> .

Özel durumlar

array, null'e eşittir.

index alt sınırından küçüktür array.

-veya-

length, sıfırdan küçüktür.

index ve length içinde arraygeçerli bir aralık belirtmeyin.

-veya-

uygulaması comparer , sıralama sırasında bir hataya neden oldu. Örneğin, comparer bir öğeyi kendisiyle karşılaştırırken 0 döndürmeyebilir.

comparer ve nulliçindeki array bir veya daha fazla öğe genel arabirimi uygulamaz IComparable<T> .

Örnekler

Aşağıdaki kod örneği, bir dizideki Sort<T>(T[], Int32, Int32) bir aralığı sıralamak için genel yöntem aşırı yüklemesini Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) ve genel yöntem aşırı yüklemesini gösterir.

Kod örneği, ReverseCompare (Visual Basic'da IComparer<string>) genel arabirimini uygulayan IComparer(Of String) adlı dizeler için alternatif bir karşılaştırıcı tanımlar. Karşılaştırıcı yöntemini çağırır ve dizelerin düşük-yüksek yerine yüksek-düşük sıralanması için karşılaştırıcıların sırasını tersine çevirme CompareTo(String) .

Kod örneği, üç otçul ve ardından üç etoburdan oluşan bir dinozor adları dizisi oluşturur ve görüntüler (kesin olarak tyrannosaurids). Genel Sort<T>(T[], Int32, Int32) yöntem aşırı yüklemesi, dizinin son üç öğesini sıralamak için kullanılır ve daha sonra görüntülenir. Genel Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>) yöntem aşırı yüklemesi, son üç öğeyi ters sırada sıralamak için ile ReverseCompare birlikte kullanılır. Kafaları iyice karışmış dinozorlar tekrar görüntüleniyor.

Note

Sort<T>(T[], IComparer<T>) ve BinarySearch<T>(T[], T, IComparer<T>) genel yöntemlerine yapılan çağrılar, Visual Basic, C# ve C++ genel tür parametresinin türünü ilk bağımsız değişkenin türünden çıkardığından, genel olmayan karşılıklarına yapılan çağrılardan farklı görünmemektedir. Microsoft ara dili (MSIL) incelemek için Ildasm.exe (IL Disassembler) kullanırsanız, genel yöntemlerin çağrıldığını görebilirsiniz.

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

Açıklamalar

ise comparernull, içindeki array belirtilen öğe aralığındaki her öğenin içindeki diğer tüm öğelerle IComparable<T>karşılaştırma yapabilmesi için genel arabirimi uygulaması array gerekir.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir; burada n olur length.

Arayanlara Notlar

.NET Framework 4 ve önceki sürümleri yalnızca Quicksort algoritmasını kullanıyordu. Quicksort, sıralama işleminin bir IndexOutOfRangeException özel durum oluşturduğu bazı durumlarda geçersiz karşılaştırıcıları tanımlar ve çağırana bir ArgumentException özel durum oluşturur. .NET Framework 4.5'den başlayarak, daha önce ArgumentException oluşturan sıralama işlemlerinin özel durum oluşturmaması mümkündür çünkü ekleme sıralama ve yığın sıralama algoritmaları geçersiz bir karşılaştırıcı algılamaz. Çoğunlukla bu, 16 öğeden küçük veya buna eşit diziler için geçerlidir.

Ayrıca bkz.

Şunlara uygulanır

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

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Belirtilen Array genel arabirimi kullanan ilk Array nesnedeki anahtarlara göre bir nesne çiftindeki IComparer<T> bir öğe aralığını sıralar (biri anahtarları, diğeri de ilgili öğeleri içerir).

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

Tür Parametreleri

TKey

Anahtar dizisinin öğelerinin türü.

TValue

Items dizisinin öğelerinin türü.

Parametreler

keys
TKey[]

Sıralanacak anahtarları içeren tek boyutlu, sıfır tabanlı Array .

items
TValue[]

içindeki anahtarlara Arraykarşılık gelen öğeleri içeren veya keys yalnızca nullsıralamak için tek boyutlu, sıfır tabanlıdırkeys.

index
Int32

Sıralanacak aralığın başlangıç dizini.

length
Int32

Sıralanacak aralıktaki öğelerin sayısı.

comparer
IComparer<TKey>

Öğeleri IComparer<T> karşılaştırırken kullanılacak genel arabirim uygulaması veya null her öğenin genel arabirim uygulamasını kullanmak IComparable<T> .

Özel durumlar

keys, null'e eşittir.

index alt sınırından küçüktür keys.

-veya-

length, sıfırdan küçüktür.

items değeri değildir nullve alt sınırı keys alt sınırıyla itemseşleşmiyor.

-veya-

items değildir nullve uzunluğu değerinden keysitemsbüyüktür.

-veya-

index ve length içinde keysArraygeçerli bir aralık belirtmeyin.

-veya-

items değil nullve indexlength içinde itemsArraygeçerli bir aralık belirtmeyin.

-veya-

uygulaması comparer , sıralama sırasında bir hataya neden oldu. Örneğin, comparer bir öğeyi kendisiyle karşılaştırırken 0 döndürmeyebilir.

comparer , nullve içindeki keysArray bir veya daha fazla öğe genel arabirimi uygulamaz IComparable<T> .

Örnekler

Aşağıdaki kod örneği, anahtarları ve Sort<TKey,TValue>(TKey[], TValue[]) değerleri temsil eden dizi çiftlerini sıralamak için , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), ve genel yöntem aşırı yüklemelerini gösterirSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>).

Kod örneği, Visual Basic) genel arabiriminde ReverseCompare(IComparer<string> uygulayan IComparer(Of String) adlı dizeler için alternatif bir karşılaştırıcı tanımlar. Karşılaştırıcı yöntemini çağırır ve dizelerin düşük-yüksek yerine yüksek-düşük sıralanması için karşılaştırıcıların sırasını tersine çevirme CompareTo(String) .

Kod örneği, bir dinozor adları dizisi (anahtarlar) ve her dinozorun metre cinsinden maksimum uzunluğunu (değerler) temsil eden bir tamsayı dizisi oluşturur ve görüntüler. Ardından diziler birkaç kez sıralanır ve görüntülenir:

Note

Visual Basic, C# ve C++ genel tür parametresinin türünü ilk iki bağımsız değişkenin türünden çıkardığından, genel yöntemlere yapılan çağrılar, genel olmayan karşılıklarına yapılan çağrılardan farklı görünmemektedir. Microsoft ara dili (MSIL) incelemek için Ildasm.exe (IL Disassembler) kullanırsanız, genel yöntemlerin çağrıldığını görebilirsiniz.

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.

Açıklamalar

içindeki her anahtarın keysArray içinde itemsArraykarşılık gelen bir öğesi vardır. Sıralama sırasında bir anahtar yeniden konumlandırıldığında, içindeki itemsArray ilgili öğe benzer şekilde yeniden konumlandırılır. Bu nedenle, içindeki itemsArray ilgili anahtarların keysArraydüzenlemesine göre sıralanır.

ise comparernull, içindeki keysArray belirtilen öğe aralığındaki her anahtar, diğer tüm anahtarlarla karşılaştırma yapabilmesi için genel arabirimi uygulamalıdır IComparable<T> .

Anahtarlardan daha fazla öğe varsa sıralayabilirsiniz, ancak karşılık gelen anahtarı olmayan öğeler sıralanmaz. Öğelerden daha fazla anahtar varsa sıralayamazsınız; bunu yapmak bir ArgumentExceptionoluşturur.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir; burada n olur length.

Arayanlara Notlar

.NET Framework 4 ve önceki sürümleri yalnızca Quicksort algoritmasını kullanıyordu. Quicksort, sıralama işleminin bir IndexOutOfRangeException özel durum oluşturduğu bazı durumlarda geçersiz karşılaştırıcıları tanımlar ve çağırana bir ArgumentException özel durum oluşturur. .NET Framework 4.5'den başlayarak, daha önce ArgumentException oluşturan sıralama işlemlerinin özel durum oluşturmaması mümkündür çünkü ekleme sıralama ve yığın sıralama algoritmaları geçersiz bir karşılaştırıcı algılamaz. Çoğunlukla bu, 16 öğeden küçük veya buna eşit diziler için geçerlidir.

Ayrıca bkz.

Şunlara uygulanır

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

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Bir nesne çiftini Array (biri anahtarları, diğeri de ilgili öğeleri içerir) her anahtarın genel arabirim uygulamasını kullanan Array ilk IComparable<T> anahtarlara göre sıralar.

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

Tür Parametreleri

TKey

Anahtar dizisinin öğelerinin türü.

TValue

Items dizisinin öğelerinin türü.

Parametreler

keys
TKey[]

Sıralanacak anahtarları içeren tek boyutlu, sıfır tabanlı Array .

items
TValue[]

içindeki anahtarlara Arraykarşılık gelen öğeleri içeren veya keys yalnızca nullsıralamak için tek boyutlu, sıfır tabanlıdırkeys.

Özel durumlar

keys, null'e eşittir.

items değeri değildir nullve alt sınırı keys alt sınırıyla itemseşleşmiyor.

-veya-

items değildir nullve uzunluğu değerinden keysitemsbüyüktür.

içindeki keysArray bir veya daha fazla öğe genel arabirimi uygulamaz IComparable<T> .

Örnekler

Aşağıdaki kod örneği, anahtarları ve Sort<TKey,TValue>(TKey[], TValue[]) değerleri temsil eden dizi çiftlerini sıralamak için , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), ve genel yöntem aşırı yüklemelerini gösterirSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>).

Kod örneği, ReverseCompare (Visual Basic'da IComparer<string>) genel arabirimini uygulayan IComparer(Of String) adlı dizeler için alternatif bir karşılaştırıcı tanımlar. Karşılaştırıcı yöntemini çağırır ve dizelerin düşük-yüksek yerine yüksek-düşük sıralanması için karşılaştırıcıların sırasını tersine çevirme CompareTo(String) .

Kod örneği, bir dinozor adları dizisi (anahtarlar) ve her dinozorun metre cinsinden maksimum uzunluğunu (değerler) temsil eden bir tamsayı dizisi oluşturur ve görüntüler. Ardından diziler birkaç kez sıralanır ve görüntülenir:

Note

Visual Basic, C# ve C++ genel tür parametresinin türünü ilk iki bağımsız değişkenin türünden çıkardığından, genel yöntemlere yapılan çağrılar, genel olmayan karşılıklarına yapılan çağrılardan farklı görünmemektedir. Microsoft ara dili (MSIL) incelemek için Ildasm.exe (IL Disassembler) kullanırsanız, genel yöntemlerin çağrıldığını görebilirsiniz.

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.

Açıklamalar

içindeki her anahtarın keysArray içinde itemsArraykarşılık gelen bir öğesi vardır. Sıralama sırasında bir anahtar yeniden konumlandırıldığında, içindeki itemsArray ilgili öğe benzer şekilde yeniden konumlandırılır. Bu nedenle, içindeki itemsArray ilgili anahtarların keysArraydüzenlemesine göre sıralanır.

içindeki keysArray her anahtar, diğer tüm anahtarlarla karşılaştırma yapabilmesi için genel arabirimi uygulamalıdır IComparable<T> .

Anahtarlardan daha fazla öğe varsa sıralayabilirsiniz, ancak karşılık gelen anahtarı olmayan öğeler sıralanmaz. Öğelerden daha fazla anahtar varsa sıralayamazsınız; bunu yapmak bir ArgumentExceptionoluşturur.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir ve burada n öğesinin Length değeridir array.

Ayrıca bkz.

Şunlara uygulanır

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

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Bir nesne çiftini Array (biri anahtarları, diğeri de ilgili öğeleri içerir) belirtilen Array genel arabirimi kullanan ilk IComparer<T> anahtarlara göre sıralar.

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

Tür Parametreleri

TKey

Anahtar dizisinin öğelerinin türü.

TValue

Items dizisinin öğelerinin türü.

Parametreler

keys
TKey[]

Sıralanacak anahtarları içeren tek boyutlu, sıfır tabanlı Array .

items
TValue[]

içindeki anahtarlara Arraykarşılık gelen öğeleri içeren veya keys yalnızca nullsıralamak için tek boyutlu, sıfır tabanlıdırkeys.

comparer
IComparer<TKey>

Öğeleri IComparer<T> karşılaştırırken kullanılacak genel arabirim uygulaması veya null her öğenin genel arabirim uygulamasını kullanmak IComparable<T> .

Özel durumlar

keys, null'e eşittir.

items değeri değildir nullve alt sınırı keys alt sınırıyla itemseşleşmiyor.

-veya-

items değildir nullve uzunluğu değerinden keysitemsbüyüktür.

-veya-

uygulaması comparer , sıralama sırasında bir hataya neden oldu. Örneğin, comparer bir öğeyi kendisiyle karşılaştırırken 0 döndürmeyebilir.

comparer , nullve içindeki keysArray bir veya daha fazla öğe genel arabirimi uygulamaz IComparable<T> .

Örnekler

Aşağıdaki kod örneği, anahtarları ve Sort<TKey,TValue>(TKey[], TValue[]) değerleri temsil eden dizi çiftlerini sıralamak için , []Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>), , Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32)ve genel yöntem aşırı yüklemelerini gösterirSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>).

Kod örneği, ReverseCompare (Visual Basic'da IComparer<string>) genel arabirimini uygulayan IComparer(Of String) adlı dizeler için alternatif bir karşılaştırıcı tanımlar. Karşılaştırıcı yöntemini çağırır ve dizelerin düşük-yüksek yerine yüksek-düşük sıralanması için karşılaştırıcıların sırasını tersine çevirme CompareTo(String) .

Kod örneği, bir dinozor adları dizisi (anahtarlar) ve her dinozorun metre cinsinden maksimum uzunluğunu (değerler) temsil eden bir tamsayı dizisi oluşturur ve görüntüler. Ardından diziler birkaç kez sıralanır ve görüntülenir:

Note

Visual Basic, C# ve C++ genel tür parametresinin türünü ilk iki bağımsız değişkenin türünden çıkardığından, genel yöntemlere yapılan çağrılar, genel olmayan karşılıklarına yapılan çağrılardan farklı görünmemektedir. Microsoft ara dili (MSIL) incelemek için Ildasm.exe (IL Disassembler) kullanırsanız, genel yöntemlerin çağrıldığını görebilirsiniz.

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.

Açıklamalar

içindeki her anahtarın keysArray içinde itemsArraykarşılık gelen bir öğesi vardır. Sıralama sırasında bir anahtar yeniden konumlandırıldığında, içindeki itemsArray ilgili öğe benzer şekilde yeniden konumlandırılır. Bu nedenle, içindeki itemsArray ilgili anahtarların keysArraydüzenlemesine göre sıralanır.

ise comparernulliçindeki her anahtar, diğer tüm anahtarlarla keysArray karşılaştırma yapabilmesi için genel arabirimi uygulamalıdır IComparable<T> .

Anahtarlardan daha fazla öğe varsa sıralayabilirsiniz, ancak karşılık gelen anahtarı olmayan öğeler sıralanmaz. Öğelerden daha fazla anahtar varsa sıralayamazsınız; bunu yapmak bir ArgumentExceptionoluşturur.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir ve burada n öğesinin Length değeridir array.

Arayanlara Notlar

.NET Framework 4 ve önceki sürümleri yalnızca Quicksort algoritmasını kullanıyordu. Quicksort, sıralama işleminin bir IndexOutOfRangeException özel durum oluşturduğu bazı durumlarda geçersiz karşılaştırıcıları tanımlar ve çağırana bir ArgumentException özel durum oluşturur. .NET Framework 4.5'den başlayarak, daha önce ArgumentException oluşturan sıralama işlemlerinin özel durum oluşturmaması mümkündür çünkü ekleme sıralama ve yığın sıralama algoritmaları geçersiz bir karşılaştırıcı algılamaz. Çoğunlukla bu, 16 öğeden küçük veya buna eşit diziler için geçerlidir.

Ayrıca bkz.

Şunlara uygulanır

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

Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs
Kaynak:
Array.cs

Her bir anahtarın genel arabirim uygulamasını kullanan Array ilk Array anahtarlara göre, bir nesne çiftindeki IComparable<T> bir öğe aralığını sıralar (biri anahtarları, diğeri de ilgili öğeleri içerir).

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)

Tür Parametreleri

TKey

Anahtar dizisinin öğelerinin türü.

TValue

Items dizisinin öğelerinin türü.

Parametreler

keys
TKey[]

Sıralanacak anahtarları içeren tek boyutlu, sıfır tabanlı Array .

items
TValue[]

içindeki anahtarlara Arraykarşılık gelen öğeleri içeren veya keys yalnızca nullsıralamak için tek boyutlu, sıfır tabanlıdırkeys.

index
Int32

Sıralanacak aralığın başlangıç dizini.

length
Int32

Sıralanacak aralıktaki öğelerin sayısı.

Özel durumlar

keys, null'e eşittir.

index alt sınırından küçüktür keys.

-veya-

length, sıfırdan küçüktür.

items değeri değildir nullve alt sınırı keys alt sınırıyla itemseşleşmiyor.

-veya-

items değildir nullve uzunluğu değerinden keysitemsbüyüktür.

-veya-

index ve length içinde keysArraygeçerli bir aralık belirtmeyin.

-veya-

items değil nullve indexlength içinde itemsArraygeçerli bir aralık belirtmeyin.

içindeki keysArray bir veya daha fazla öğe genel arabirimi uygulamaz IComparable<T> .

Örnekler

Aşağıdaki kod örneği, anahtarları ve Sort<TKey,TValue>(TKey[], TValue[]) değerleri temsil eden dizi çiftlerini sıralamak için , Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)Sort<TKey,TValue>(TKey[], TValue[], Int32, Int32), ve genel yöntem aşırı yüklemelerini gösterirSort<TKey,TValue>(TKey[], TValue[], Int32, Int32, IComparer<TKey>).

Kod örneği, ReverseCompare (Visual Basic'da IComparer<string>) genel arabirimini uygulayan IComparer(Of String) adlı dizeler için alternatif bir karşılaştırıcı tanımlar. Karşılaştırıcı yöntemini çağırır ve dizelerin düşük-yüksek yerine yüksek-düşük sıralanması için karşılaştırıcıların sırasını tersine çevirme CompareTo(String) .

Kod örneği, bir dinozor adları dizisi (anahtarlar) ve her dinozorun metre cinsinden maksimum uzunluğunu (değerler) temsil eden bir tamsayı dizisi oluşturur ve görüntüler. Ardından diziler birkaç kez sıralanır ve görüntülenir:

Note

Visual Basic, C# ve C++ genel tür parametresinin türünü ilk iki bağımsız değişkenin türünden çıkardığından, genel yöntemlere yapılan çağrılar, genel olmayan karşılıklarına yapılan çağrılardan farklı görünmemektedir. Microsoft ara dili (MSIL) incelemek için Ildasm.exe (IL Disassembler) kullanırsanız, genel yöntemlerin çağrıldığını görebilirsiniz.

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.

Açıklamalar

içindeki her anahtarın keysArray içinde itemsArraykarşılık gelen bir öğesi vardır. Sıralama sırasında bir anahtar yeniden konumlandırıldığında, içindeki itemsArray ilgili öğe benzer şekilde yeniden konumlandırılır. Bu nedenle, içindeki itemsArray ilgili anahtarların keysArraydüzenlemesine göre sıralanır.

içindeki belirtilen öğe aralığındaki keysArray her anahtar, diğer tüm anahtarlarla karşılaştırma yapabilmesi için genel arabirimi uygulamalıdır IComparable<T> .

Anahtarlardan daha fazla öğe varsa sıralayabilirsiniz, ancak karşılık gelen anahtarı olmayan öğeler sıralanmaz. Öğelerden daha fazla anahtar varsa sıralayamazsınız; bunu yapmak bir ArgumentExceptionoluşturur.

Sıralama başarıyla tamamlanmazsa, sonuçlar tanımlanmamış olur.

Bu yöntem, aşağıdaki gibi introspective sort (introsort) algoritmasını kullanır:

  • Bölüm boyutu 16 öğeden küçük veya buna eşitse ekleme sıralama algoritması kullanır.

  • Bölüm sayısı 2 * GünlükN'yi aşarsa, burada N giriş dizisinin aralığıdır, bir Heapsort algoritması kullanır.

  • Aksi takdirde, bir Quicksort algoritması kullanır.

Bu uygulama kararsız bir sıralama gerçekleştirir; diğer bir ifadeyle, iki öğe eşitse, sıraları korunmayabilir. Buna karşılık, kararlı bir sıralama eşit öğelerin sırasını korur.

Bu yöntem bir O(n günlük n) işlemidir; burada n olur length.

Ayrıca bkz.

Şunlara uygulanır