C# program to sort an array in descending order

CsharpProgrammingServer Side Programming

Initialize the array.

int[] myArr = new int[5] {98, 76, 99, 32, 77};

Compare the first element in the array with the next element to find the largest element, then the second largest, etc.

if(myArr[i] < myArr[j]) {
   temp = myArr[i];
   myArr[i] = myArr[j];
   myArr[j] = temp;
}

Above, i and j are initially set to.

i=0;
j=i+1;

Try to run the following code to sort an array in descending order.

Example

 Live Demo

using System;
public class Demo {
   public static void Main() {
      int[] myArr = new int[5] {98, 76, 99, 32, 77};
      int i, j, temp;
      Console.Write("Elements: \n");
      for(i=0;i<5;i++) {
         Console.Write("{0} ",myArr[i]);
      }
      for(i=0; i<5; i++) {
         for(j=i+1; j<5; j++) {
            if(myArr[i] < myArr[j]) {
               temp = myArr[i];
               myArr[i] = myArr[j];
               myArr[j] = temp;
            }
         }
      }
      Console.Write("\nDescending order:\n");
      for(i=0; i<5; i++) {
         Console.Write("{0} ", myArr[i]);
      }
      Console.Write("\n\n");
   }
}

Output

Elements:
98 76 99 32 77
Descending order:
99 98 77 76 32
raja
Published on 17-Sep-2018 17:52:34
Advertisements