Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
Advertisements