C# program to sort an array in descending order
1-By using built-in method
To sort an array in descending order using a built-in method in C#, you can leverage the Array.Sort method along with a custom comparer. Here's an example program that sorts an array in descending order using the Array.Sort method with a custom comparer:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 5, 2, 8, 3, 1, 9, 4, 6, 7 };
// Sort the array in descending order using Array.Sort and custom comparer
Array.Sort(numbers, (a, b) => b.CompareTo(a));
Console.WriteLine("Sorted array in descending order:");
foreach (int num in numbers) {
Console.Write(num + " ");
}
}
}
In this program, we have an array of integers called numbers with unsorted values. We utilize the Array.Sort method and provide a custom comparer using a lambda expression (a, b) => b.CompareTo(a). This comparer compares elements in descending order by comparing b to a instead of the default ascending order comparison.
The Array.Sort method with the custom comparer modifies the original array in-place, rearranging its elements in descending order.
The program outputs the sorted array in descending order:
Sorted array in descending order:
9 8 7 6 5 4 3 2 1
By using the Array.Sort method with a custom comparer, you can conveniently sort an array in descending order without having to implement a sorting algorithm from scratch.
2-By using sorting algorithm
To sort an array in descending order using C#, you can modify the previous example by changing the comparison condition in the sorting algorithm. Here's a modified version of the program that sorts an array in descending order using the Bubble Sort algorithm:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 5, 2, 8, 3, 1, 9, 4, 6, 7 };
// Sort the array in descending order using Bubble Sort
BubbleSortDescending(numbers);
Console.WriteLine("Sorted array in descending order:");
foreach (int num in numbers) {
Console.Write(num + " ");
}
}
public static void BubbleSortDescending(int[] arr) {
int n = arr.Length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
In this modified program, the BubbleSortDescending method uses the same Bubble Sort algorithm as before, but with a reversed comparison condition. Instead of swapping elements when arr[j] > arr[j + 1], we swap them when arr[j] < arr[j + 1]. This change ensures that the largest element moves towards the beginning of the array in each iteration.
The program outputs the sorted array in descending order:
Sorted array in descending order:
9 8 7 6 5 4 3 2 1
Keep in mind that Bubble Sort, while simple to understand, is not the most efficient sorting algorithm for large arrays. If performance is a concern, consider using more efficient algorithms like Quick Sort or Merge Sort.