How do you sort a C# array in descending or reverse order?  A simple way is to sort the array in ascending order, then reverse it:

int[] array = new int[] { 3, 1, 4, 5, 2 };
Array.Sort<int>( array );
Array.Reverse( array );

Of course, this is not efficient for large arrays.

A better approach is to create a custom Comparer.  Following is a nice generics class that will sort an array in descending order. Note that the object type must be comparable (inherit from IComparable) as any useful class should.

static public class ArraySorter<T>
    where T : IComparable
{
    static public void SortDescending( T[] array )
    {
        Array.Sort<T>( array, s_Comparer );
    }
    static private ReverseComparer s_Comparer = new ReverseComparer();
    private class ReverseComparer : IComparer<T>
    {
        public int Compare( T object1, T object2 )
        {
            return -((IComparable)object1).CompareTo( object2 );
        }
    }
}

Here’s a simple console program to test it:

using System;
using System.Collections.Generic;

namespace CSharp411
{
    class Program
    {
        static void Main( string[] args )
        {
            int[] array = new int[] { 3, 1, 4, 5, 2 };
            ArraySorter<int>.SortDescending( array );
            WriteArray( array );
            Console.ReadLine();
        }
        static private void WriteArray( int[] array )
        {
            foreach (int i in array)
            {
                Console.WriteLine( i );
            }
        }
    }
    static public class ArraySorter<T>
        where T : IComparable
    {
        static public void SortDescending( T[] array )
        {
            Array.Sort<T>( array, s_Comparer );
        }
        static private ReverseComparer s_Comparer = new ReverseComparer();
        private class ReverseComparer : IComparer<T>
        {
            public int Compare( T object1, T object2 )
            {
                return -((IComparable)object1).CompareTo( object2 );
            }
        }
    }
}
Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot