How to Sort an Array in C#?
In C#, you can sort an array using the Array.Sort()
method for arrays of primitive types or arrays of types that implement the IComparable
interface.
using System;
class Program
{
static void Main(string[] args)
{
// Sample array of integers
int[] numbers = { 5, 2, 9, 1, 6 };
// Sorting the array
Array.Sort(numbers);
// Displaying the sorted array
Console.WriteLine("Sorted Numbers:");
foreach (int num in numbers)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
We declared an array of integers and then used Array.Sort()
to sort the array in ascending order.
Output:
Sorted Numbers:
1 2 5 6 9
Comments (0)