Better way to sort array in descending order

后端 未结 7 2160
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 09:54

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

相关标签:
7条回答
  • 2020-12-01 10:40

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

    0 讨论(0)
  • 2020-12-01 10:43

    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();
    
    0 讨论(0)
  • 2020-12-01 10:48
    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);
            }
    
        }
    
    0 讨论(0)
  • 2020-12-01 10:53

    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.

    0 讨论(0)
  • 2020-12-01 11:00

    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)

    0 讨论(0)
  • 2020-12-01 11:00

    For in-place sorting in descending order:

    int[] numbers = { 1, 2, 3 };
    Array.Sort(numbers, (a, b) => b - a);
    

    For out-of-place sorting (no changes to input array):

    int[] numbers = { 1, 2, 3 };
    var sortedNumbers = numbers.OrderByDescending(x => x).ToArray();
    
    0 讨论(0)
提交回复
热议问题