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
Yes, you can pass predicate to sort. That would be your reverse implementation.
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();
class Program
{
private static int[] table;
static void Main(string[] args)
{
int[] ints = new int[] { 6, 2, 5, 99, 55 };
table = ints.OrderByDescending(x => x).ToArray();
foreach (var item in table)
{
Console.WriteLine(item);
}
}
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 - a);
For out-of-place sorting (no changes to input array):
int[] numbers = { 1, 2, 3 };
var sortedNumbers = numbers.OrderByDescending(x => x).ToArray();