In this problem we will learn how to sort array in descending order . In this solution for more clarification we use three for loops so everyone can easily understand the function of descending sorting.
Source Code
#include<iostream> using namespace std; int main () { int num [5]; int temp =0; for (int i =0; i<5;i++) { cout<<" Enter Your Number : "; cin>>num[i]; } cout<<endl; cout<<" Your Number Before Sorting in Descending order \n "; for (int i =0;i<5;i++) { cout<<endl<<num[i]; } cout<<" \n Your Number After Sorting in Descending order "; for (int i =0;i<5;i++) { for (int k =0;k<5-1;k++) { if (num[k+1] > num[k]) { temp = num[k]; num[k]=num[k+1]; num[k+1]=temp; } } } for (int m =0;m <5;m ++) { cout<<endl<<num[m]; } }
That is not the c++ way to do it. This is much easier:
ReplyDeletebool desc (int i,int j) { return (i>j); }
void example() {
std::vector a = {1, 2, 3, 4, 5};
std::sort(a.begin(), a.end(), desc);
for (auto b : a) {
std::cout << b << std::endl;
}
}
I left out the user part and used a vector.