Saturday 2 August 2014

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

Structure of the Problem Requirements 


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 of array.The Program will take 5 integers from user and then show them to user as user enter with the message "your number before descending order" after this bubble sorting logic apply to that array and sort them in descending order.

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
Sorted Array in Descending Order 





Share it Please
asad

About Author!

Asad Niazi is Software Engineer , Programmer, Web Developers and a young mentor of Tech Solutions Desk and Blogging Solutions . Asad Love to writes about Technology, Programming, Blogging and make money online.

2 comments: Post Yours! Read Comment Policy!▼
Important Note:
We have Zero Tolerance to Spam. Chessy Comments and Comments with Links will be deleted immediately upon our review.

  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
  2. Vector is new Concept.. Many ways to Sort Depend on Requirement :)

    ReplyDelete