79

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

1
  • 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. Commented Jul 10, 2019 at 16:40

7 Answers 7

82

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();
Sign up to request clarification or add additional context in comments.

4 Comments

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 ?
@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.
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.
@JYL You're not wrong. OrderBy() is a different algorithm than Array.Sort(). Anyone interested see this post stackoverflow.com/questions/1832684/…
80

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.

4 Comments

This, or just add a - (minus sign) before CompareTo
Or simply Array.Sort(array, (a, b) => b.CompareTo(a)) for a reverse sort.
true, but sometimes slower… so it depends what you want and what you sort, see: stackoverflow.com/questions/6842090/…
Or do this: 'Array.Sort<int>(array, (i1,i2) => i2.CompareTo(i1))'
14

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();

2 Comments

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)
@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.
12

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)

1 Comment

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)
2

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

Comments

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

Comments

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);
        }

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.