72

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

santosh singh
  • 27,666
  • 26
  • 83
  • 129
  • 2
    If there is no huge constraint on time, I would stick with Array.Sort followed by Array.Reverse. Reason is readability is very high, and asymptotically, Array.Reverse() is simply a O(n) operation. – user3613932 Jul 10 '19 at 16:40

7 Answers7

75

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();
Ilya Smagin
  • 5,992
  • 11
  • 40
  • 57
  • 10
    This is a short working code, but if the array is large, it is not very efficient (in performance term), because the array is converted to list first, then sorted, and finally converted to array. Am I wrong ? – JYL Mar 25 '11 at 09:14
  • @Ilyusha, If consider `int` from perspective of composite objects (not simple objects), then `int` it's the same object like others, because either of two objects you need to compare till 1st difference, so O(n) it's impossible result. – Kirill Polishchuk Jun 29 '11 at 15:28
  • Google translate of @Ilyusha's (which I still don't fully understand): Integers can be sorted in O (n). There is a view in a very low level, the number represented by a sequence of bits. Then, technically, to compare two numbers require fewer resources than the reading of two of them. This suggests an unusual way as the storage and comparing, so sisyarpe about this there can be no question. – zod Aug 15 '12 at 08:27
  • @JYL You're not wrong. `OrderBy()` is a different algorithm than `Array.Sort()`. Anyone interested see this post https://stackoverflow.com/questions/1832684/c-sharp-sort-and-orderby-comparison – Kellen Stuart Nov 20 '21 at 04:11
72

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.

JYL
  • 8,228
  • 5
  • 39
  • 63
11

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)

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
  • 1
    bear in mind, u might get integer overflow for b - a when b is int.MinValue and a is any positive number. Better always to do b.CompareTo(a) – Daniel B Dec 16 '20 at 23:17
10

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();
Alex Aza
  • 76,499
  • 26
  • 155
  • 134
  • 1
    bear that in mind, u might get integer overflow for b - a when b is int.MinValue and a is any positive number. Better always do b.CompareTo(a) – Daniel B Nov 29 '20 at 21:02
  • @DanielB it's quite an edge case with int overflow, but other than that if you are sure your input data are not of that kind, this is the shortest 1-line code for sorting descending, and should be higher in top answers. – tytyryty Jul 22 '23 at 07:17
2

Yes, you can pass predicate to sort. That would be your reverse implementation.

Sasha Reminnyi
  • 3,442
  • 2
  • 23
  • 27
2

You may specify a comparer(IComparer implementation) as a parameter in Array.Sort, the order of sorting actually depends on comparer. The default comparer is used in ascending sorting

Tony Kh
  • 1,512
  • 11
  • 8
0
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);
        }

    }
Błażej
  • 125
  • 2
  • 11