A2oz

How to Sort a Number Array in C#?

Published in Programming 1 min read

You can sort a number array in C# using the built-in Array.Sort() method. This method sorts the array in ascending order by default.

Here's how you can use it:

int[] numbers = { 5, 2, 8, 1, 9 };

// Sort the array in ascending order
Array.Sort(numbers);

// Print the sorted array
foreach (int number in numbers)
{
    Console.WriteLine(number);
}

Output:

1
2
5
8
9

Practical Insights:

  • The Array.Sort() method uses the QuickSort algorithm, which is generally efficient for sorting large arrays.
  • You can sort arrays of other data types, such as strings, using the same method.
  • If you need to sort in descending order, you can use the Array.Reverse() method after sorting in ascending order.

Example:

int[] numbers = { 5, 2, 8, 1, 9 };

// Sort in ascending order
Array.Sort(numbers);

// Reverse the array to sort in descending order
Array.Reverse(numbers);

// Print the sorted array
foreach (int number in numbers)
{
    Console.WriteLine(number);
}

Output:

9
8
5
2
1

Related Articles