C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Write: We enumerate the integers in the sorted array, printing them to the console.
ConsoleC# program that uses simple Array.Sort overload
using System;
class Program
{
static void Main()
{
// Simple sort call.
int[] values = { 4, 7, 2, 0 };
Array.Sort(values);
foreach (int value in values)
{
Console.Write(value);
Console.Write(' ');
}
Console.WriteLine();
}
}
Output
0 2 4 7
Next: This Array reference is passed to the Array.Sort method, which can sort the elements.
And: Before program completion, we display the sorted elements in the Array reference.
C# program that uses Array reference type
using System;
class Program
{
static void Main()
{
// 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();
}
}
Output
0 2 4 7
Arguments: We call Array.Sort with 2 array arguments. The first is the keys array and the second, the values array.
Finally: The program prints out the keys array in its sorted order, and the values array in its sorted order.
C# program that sorts keys and values
using System;
class Program
{
static void Main()
{
// 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();
}
}
Output
0 2 4 7
4 3 1 2
Arguments: These are the array reference (int[]), the starting index (0) and the number of elements to sort past that index.
Note: This program uses 0, 3 to sort only the first three elements. It sorts a range of elements.
Tip: You can see in the results that the first three elements are sorted in ascending numeric order.
And: The fourth element 0 is still at the end because it was not included in the sorting operation.
C# program that sorts range of elements
using System;
class Program
{
static void Main()
{
// 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();
}
}
Output
2 4 7 0