C# program to sort an array in descending order


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: 
");       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("
Descending order:
");       for(i=0; i<5; i++) {          Console.Write("{0} ", myArr[i]);       }       Console.Write("

");    } }

Output

Elements:
98 76 99 32 77
Descending order:
99 98 77 76 32

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements