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#?
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.
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).
rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With