Export (0) Print
Expand All

Array.Sort Method (Array, Array)

.NET Framework 1.1

Sorts a pair of one-dimensional Array objects (one contains the keys and the other contains the corresponding items) based on the keys in the first Array using the IComparable interface implemented by each key.

[Visual Basic]
Overloads Public Shared Sub Sort( _
   ByVal keys As Array, _
   ByVal items As Array _
)
[C#]
public static void Sort(
 Array keys,
 Array items
);
[C++]
public: static void Sort(
 Array* keys,
 Array* items
);
[JScript]
public static function Sort(
   keys : Array,
 items : Array
);

Parameters

keys
The one-dimensional Array that contains the keys to sort.
items
The one-dimensional Array that contains the items that correspond to each of the keys in the keys Array.

-or-

A null reference (Nothing in Visual Basic) to sort only the keys Array.

Exceptions

Exception Type Condition
ArgumentNullException keys is a null reference (Nothing in Visual Basic).
RankException The keys Array is multidimensional.

-or-

The items Array is multidimensional.

ArgumentException items is not a null reference (Nothing in Visual Basic), and the lower bound of keys does not match the lower bound of items.

-or-

items is not a null reference (Nothing), and the length of keys does not match the length of items.

InvalidOperationException One or more elements in the keys Array do not implement the IComparable interface.

Remarks

Each key in the keys Array has a corresponding item in the items Array. When a key is repositioned during the sorting, the corresponding item in the items Array is similarly repositioned. Therefore, the items Array is sorted according to the arrangement of the corresponding keys in the keys Array.

Each key in the keys Array must implement the IComparable interface to be capable of comparisons with every other key.

If the sort is not successfully completed, the results are undefined.

This method uses the QuickSort algorithm. This is an O(n ^2) operation, where n is the number of elements to sort, with an average of θ(n log n).

This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.

Example

[Visual Basic, C#, C++] The following example shows how to sort two associated arrays where the first array contains the keys and the second array contains the values. Sorts are done using the default comparer and a custom comparer that reverses the sort order. Note that the result might vary depending on the current CultureInfo.

[Visual Basic] 
Imports System
Imports System.Collections

Public Class SamplesArray

   Public Class myReverserClass
      Implements IComparer

      ' Calls CaseInsensitiveComparer.Compare with the parameters reversed.
      Function Compare(x As [Object], y As [Object]) As Integer _
         Implements IComparer.Compare
         Return New CaseInsensitiveComparer().Compare(y, x)
      End Function 'IComparer.Compare

   End Class 'myReverserClass


   Public Shared Sub Main()

      ' Creates and initializes a new Array and a new custom comparer.
      Dim myKeys As [String]() =  {"red", "GREEN", "YELLOW", "BLUE", "purple", "black", "orange"}
      Dim myValues As [String]() =  {"strawberries", "PEARS", "LIMES", "BERRIES", "grapes", "olives", "cantaloupe"}
      Dim myComparer = New myReverserClass()

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

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

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

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

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

   End Sub 'Main


   Public Shared Sub PrintKeysAndValues(myKeys() As [String], myValues() As [String])

      Dim i As Integer
      For i = 0 To myKeys.Length - 1
         Console.WriteLine("   {0,-10}: {1}", myKeys(i), myValues(i))
      Next i
      Console.WriteLine()

   End Sub 'PrintKeysAndValues

End Class 'SamplesArray


'This code produces the following output.
'
'The Array initially contains the following values:
'   red       : strawberries
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the default comparer:
'   red       : strawberries
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   YELLOW    : LIMES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting a section of the Array using the reverse case-insensitive comparer:
'   red       : strawberries
'   YELLOW    : LIMES
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   purple    : grapes
'   black     : olives
'   orange    : cantaloupe
'
'After sorting the entire Array using the default comparer:
'   black     : olives
'   BLUE      : BERRIES
'   GREEN     : PEARS
'   orange    : cantaloupe
'   purple    : grapes
'   red       : strawberries
'   YELLOW    : LIMES
'
'After sorting the entire Array using the reverse case-insensitive comparer:
'   YELLOW    : LIMES
'   red       : strawberries
'   purple    : grapes
'   orange    : cantaloupe
'   GREEN     : PEARS
'   BLUE      : BERRIES
'   black     : olives


[C#] 
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

*/


[C++] 
#using <mscorlib.dll>

using namespace System;
using namespace System::Collections;

public __gc class myReverserClass : public IComparer
{
   // Calls CaseInsensitiveComparer::Compare with the parameters reversed.
   int IComparer::Compare(Object* x, Object* y) {
      return((new CaseInsensitiveComparer())->Compare(y, x));
   }
};

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

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

   // Displays the values of the Array.
   Console::WriteLine(S"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(S"After sorting a section of the Array using the default comparer:");


   // Sorts a section of the Array using the reverse case-insensitive comparer.
   Array::Sort(myKeys, myValues, 1, 3, myComparer);
   Console::WriteLine(S"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(S"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(S"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

*/

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, Common Language Infrastructure (CLI) Standard

See Also

Array Class | Array Members | System Namespace | Array.Sort Overload List | IComparable | BinarySearch | Performing Culture-Insensitive String Operations in Arrays

Show:
© 2014 Microsoft