Write a Program in C++ which sort array in descending order

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];
} }

Output of the Program


C++ Array Programming



Share on Google Plus

About Asad

Asad Niazi is Software Engineer , Programmer, Web Developer and a young mentor of BloggersTown and PProgramming. Asad Love to writes about Technology, Programming, Blogging and make money online.

1 comments:

  1. That is not the c++ way to do it. This is much easier:

    bool 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.

    ReplyDelete