C# Sort Arrays
Introduction to Sorting Arrays
Sorting is the process of arranging elements in a specific order, such as ascending or descending. It is one of the most common operations performed on collections of data.
In C#, arrays can be sorted easily using built-in methods from the System namespace, most commonly Array.Sort().
Sorting with Array.Sort()
The Array.Sort() method sorts the elements of an array in ascending order by default.
It works with numeric arrays, strings, and other types that implement IComparable.
Example
using System;
namespace SortArrayExample
{
class Program
{
static void Main(string[] args)
{
int[] numbers = { 5, 2, 9, 1, 5, 6 };
Array.Sort(numbers);
Console.WriteLine("Sorted array:");
foreach (int num in numbers)
{
Console.Write(num + " ");
}
}
}
}
Output
Sorted array: 1 2 5 5 6 9
Sorting in Descending Order
To sort in descending order, you can call Array.Sort() to sort ascending and then use Array.Reverse() to flip the order.
This approach works for numbers, strings, or any comparable data type.
Example
using System;
namespace SortDescendingExample
{
class Program
{
static void Main(string[] args)
{
string[] names = { "David", "Alice", "Bob" };
Array.Sort(names);
Array.Reverse(names);
Console.WriteLine("Sorted names in descending order:");
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
}
Output
Sorted names in descending order: David Bob Alice