Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to sort array in descending order

Tags:

c#

sorting

linq

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#?

like image 540
santosh singh Avatar asked Mar 25 '11 08:03

santosh singh


People also ask

How do you sort an array in descending order?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.

Which sort is best for descending order?

Among the classical sorting algorithms, heap sort will do well when the input turns out to be (almost) sorted in descending order, as then the max-heap construction phase will involve (almost) no swaps (while the most swaps would occur when the input was already sorted in ascending order).

Which function should we use to sort the array in descending order?

rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value.

How do I sort an int array in descending order?

You can use a reverse Comparator or Collections. reverseOrder() method to sort an object array in descending order e.g. String array, Integer array, or Double array. The Arrays. sort() method is overloaded to accept a Comparator, which can also be a reverse Comparator.


2 Answers

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 Arrays.

array = array.OrderByDescending(c => c).ToArray(); 
like image 141
Ilya Smagin Avatar answered Sep 20 '22 22:09

Ilya Smagin


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.

like image 32
JYL Avatar answered Sep 24 '22 22:09

JYL