C# Sort Arrays

Arrays often arrive in no particular order, and you may want them arranged alphabetically or from smallest to largest. C# includes helper methods in the Array class that can sort and reverse an array for you, so you rarely need to write the sorting logic yourself.

Sorting an Array

The Array.Sort() method rearranges the elements of an array in ascending order. Numbers are sorted from lowest to highest, and strings are sorted alphabetically. The method changes the original array in place rather than returning a new one.

Sorting numbers and strings

int[] numbers = {5, 1, 8, 3, 2};
Array.Sort(numbers);
foreach (int n in numbers)
{
    Console.Write(n + " "); // 1 2 3 5 8
}

string[] names = {"Mia", "Amir", "Zoe"};
Array.Sort(names);
// Amir, Mia, Zoe

Reversing an Array

The Array.Reverse() method flips the order of the elements. A common trick is to sort first and then reverse, which gives you the elements in descending order.

Sort then reverse for descending order

int[] numbers = {5, 1, 8, 3, 2};
Array.Sort(numbers);    // 1 2 3 5 8
Array.Reverse(numbers); // 8 5 3 2 1

foreach (int n in numbers)
{
    Console.Write(n + " "); // 8 5 3 2 1
}

Other Helpful Array Methods

Useful Array methods

MethodWhat it does
Array.Sort(arr)Sorts elements in ascending order
Array.Reverse(arr)Reverses the current order of elements
Array.IndexOf(arr, value)Returns the index of a value, or -1 if not found
Array.Clear(arr, 0, n)Resets the first n elements to their default value

Finding a value with IndexOf

string[] fruits = {"apple", "banana", "cherry"};
int position = Array.IndexOf(fruits, "banana");
Console.WriteLine(position); // 1
Note: Array.Sort() and Array.Reverse() modify the original array. If you need to keep the original order, make a copy first before sorting.