ArrayList.Sort Method ()
Sorts the elements in the entire ArrayList.
Assembly: mscorlib (in mscorlib.dll)
| Exception | Condition |
|---|---|
| NotSupportedException | The ArrayList is read-only. |
This method uses Array.Sort, which uses the QuickSort algorithm. The QuickSort algorithm is a comparison sort (also called an unstable sort), which means that a "less than or equal to" comparison operation determines which of two elements should occur first in the final sorted list. However, if two elements are equal, their original order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal. To perform a stable sort, you must implement a custom IComparer interface to use with the other overloads of this method.
On average, this method is an O(n log n) operation, where n is Count; in the worst case it is an O(n^2) operation.
The following code example shows how to sort the values in an ArrayList.
using System; using System.Collections; public class SamplesArrayList { public static void Main() { // Creates and initializes a new ArrayList. ArrayList myAL = new ArrayList(); myAL.Add( "The" ); myAL.Add( "quick" ); myAL.Add( "brown" ); myAL.Add( "fox" ); myAL.Add( "jumps" ); myAL.Add( "over" ); myAL.Add( "the" ); myAL.Add( "lazy" ); myAL.Add( "dog" ); // Displays the values of the ArrayList. Console.WriteLine( "The ArrayList initially contains the following values:" ); PrintValues( myAL ); // Sorts the values of the ArrayList. myAL.Sort(); // Displays the values of the ArrayList. Console.WriteLine( "After sorting:" ); PrintValues( myAL ); } public static void PrintValues( IEnumerable myList ) { foreach ( Object obj in myList ) Console.WriteLine( " {0}", obj ); Console.WriteLine(); } } /* This code produces the following output. The ArrayList initially contains the following values: The quick brown fox jumps over the lazy dog After sorting: brown dog fox jumps lazy over quick the The */
Available since 10
.NET Framework
Available since 1.1