Better way to sort array in descending order
I have a array of int which I have to sort by descending.
Since I did not find any method to sort the array in descending order.Currently I am sorting the array in descending order as below
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>( array );
Array.Reverse( array );
Now,the question is that.Is there any better way to do the same in c#?
Use LINQ OrderByDescending
method. It returns IOrderedIEnumerable<int>
, which you can convert back to Array if you need so. Generally, List<>
s are more functional then Array
s.
array = array.OrderByDescending(c => c).ToArray();
Depending on the sort order, you can do this :
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i2.CompareTo(i1)
));
... or this :
int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>(array,
new Comparison<int>(
(i1, i2) => i1.CompareTo(i2)
));
i1 and i2 are just reversed.
Sure, You can customize the sort.
You need to give the Sort() a delegate to a comparison method which it will use to sort.
Using an anonymous method:
Array.Sort<int>( array,
delegate(int a, int b)
{
return b - a; //Normal compare is a-b
});
Read more about it:
Sorting arrays
MSDN - Array.Sort Method (T[], Comparison)
For in-place sorting in descending order:
int[] numbers = { 1, 2, 3 };
Array.Sort(numbers, (a, b) => b.CompareTo(a));
For out-of-place sorting (no changes to input array):
int[] numbers = { 1, 2, 3 };
var sortedNumbers = numbers.OrderByDescending(x => x).ToArray();