Array.Sort
This method orders elements in an array. It modifies the array in-place. It handles different types of elements, including strings and ints.
Array.Sort
has some important features. We can sort 2 arrays at once: one is used as the keys array, and a second is used as the values array.
Keys
and valuesIn this example here we sort 2 arrays by a key array. First we declare the arrays (keys and values) and set the elements in them.
Array.Sort
overload that accepts two arrays. The first argument is the keys array and the second is the values array.using System; // Sort keys and values. int[] keys = { 4, 7, 2, 0 }; int[] values = { 1, 2, 3, 4 }; Array.Sort(keys, values); foreach (int key in keys) { Console.Write(key); Console.Write(' '); } Console.WriteLine(); foreach (int value in values) { Console.Write(value); Console.Write(' '); } Console.WriteLine();0 2 4 7 4 3 1 2
This program allocates an array of 4 integers. Next it calls the Array.Sort
method. This sorts the elements in-place—we do not need to assign a variable.
using System; // Simple sort call. int[] values = { 4, 7, 2, 0 }; Array.Sort(values); foreach (int value in values) { Console.Write(value); Console.Write(' '); } Console.WriteLine();0 2 4 7
This program creates an array. Then it references the newly-created int
array as an Array. We can do this because the int[]
type is derived from the Array type.
Array.Sort
method, which can sort the elements.using System; // Sort Array reference. int[] values = { 4, 7, 2, 0 }; Array array = values; Array.Sort(array); foreach (int value in array) { Console.Write(value); Console.Write(' '); } Console.WriteLine();0 2 4 7
This program creates an integer array upon the managed heap. Then, it calls the Array.Sort
method with three arguments.
int[]
), the starting index (0) and the number of elements to sort past that index.using System; // Sort range of elements. int[] values = { 4, 7, 2, 0 }; Array.Sort(values, 0, 3); foreach (int value in values) { Console.Write(value); Console.Write(' '); } Console.WriteLine();2 4 7 0
Array.Sort
has many overloads. We can modify the arguments to invoke the more sophisticated versions of the method. The List
's Sort()
method internally calls Array.Sort
.