Sort an array in descending order using C#


Declare an array and initialize −

int[] arr = new int[] {
   87,
   23,
   65,
   29,
   67
};

To sort, use the Sort() method and CompareTo() to compare and display in decreasing order −

Array.Sort < int > (arr, new Comparison < int > ((val1, val2) => val2.CompareTo(val1)));

Let us see the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Text;

public class Demo {
   public static void Main(string[] args) {
      int[] arr = new int[] {
         87,
         23,
         65,
         29,
         67
      };

      // Initial Array
      Console.WriteLine("Initial Array...");
      foreach(int items in arr) {
         Console.WriteLine(items);
      }
      Array.Sort < int > (arr, new Comparison < int > ((val1, val2) => val2.CompareTo(val1)));

      // Sorted Array
      Console.WriteLine("Sorted Array in decreasing order...");
      foreach(int items in arr) {
         Console.WriteLine(items);
      }
   }
}

Output

Initial Array...
87
23
65
29
67
Sorted Array in decreasing order...
87
67
65
29
23

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 22-Jun-2020

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements