Different ways to sort an array in descending order in C#
Last Updated :
25 Aug, 2022
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. Arranging the array’s elements from largest to smallest is termed as sorting the array in descending order. Examples:
Input : array = {5, 9, 1, 4, 6, 8};
Output : 9, 8, 6, 5, 4, 1
Input : array = {1, 9, 6, 7, 5, 9};
Output : 9 9 7 6 5 1
Input : array = {-8, 9, 7, 7, 0, 9, -9};
Output : 9 9 7 7 0 -8 -9
Method 1: Using Array.Sort() and Array.Reverse() Method First, sort the array using Array.Sort() method which sorts an array ascending order then, reverse it using Array.Reverse() method.
CSHARP
using System;
class GFG {
public static void Main()
{
int [] arr = new int [] {1, 9, 6, 7, 5, 9};
Array.Sort(arr);
Console.WriteLine( "Ascending: " );
foreach ( int value in arr)
{
Console.Write(value + " " );
}
Array.Reverse(arr);
Console.WriteLine( "\n\nDescending: " );
foreach ( int value in arr)
{
Console.Write(value + " " );
}
}
}
|
OUTPUT
Ascending:
1 5 6 7 9 9
Descending:
9 9 7 6 5 1
Method 2: Using CompareTo() Method You can also sort an array in decreasing order by using CompareTo() method.
CSHARP
using System;
class GFG {
public static void Main()
{
int [] arr = new int [] {1, 9, 6, 7, 5, 9};
Array.Sort< int >(arr, new Comparison< int >(
(i1, i2) => i2.CompareTo(i1)));
foreach ( int value in arr)
{
Console.Write(value + " ");
}
}
}
|
Method 3: Using delegate Here, first Sort() the delegate using an anonymous method.
csharp
using System;
class GFG {
public static void Main()
{
int [] arr = new int [] {1, 9, 6, 7, 5, 9};
Array.Sort< int >(arr, delegate ( int m, int n)
{ return n - m; });
foreach ( int value in arr)
{
Console.Write(value + " ");
}
}
}
|
Method 4: Using Iterative way Sort an array without using any inbuilt function by iterative way.
CSHARP
using System;
class GFG {
public static void Main()
{
int [] arr = new int [] {1, 9, 6, 7, 5, 9};
int temp;
for ( int i = 0; i < arr.Length - 1; i++)
for ( int j = i + 1; j < arr.Length; j++)
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
foreach ( int value in arr)
{
Console.Write(value + " ");
}
}
}
|
Method 5: Using LINQ descending LINQ stands for Language Integrated Query. It is a uniform query syntax which is used to retrieve and save the data from the different sources. Here, OrderByDescending sorting method is used for descending order sorting. The LINQ returns IOrderedIEnumerable, which is converted to Array using ToArray() method.
CSHARP
using System;
using System.Linq;
class GFG {
public static void Main()
{
int [] arr = new int [] {1, 9, 6, 7, 5, 9};
arr = arr.OrderByDescending(c => c).ToArray();
foreach ( int value in arr)
{
Console.Write(value + " ");
}
}
}
|
Share your thoughts in the comments
Please Login to comment...