Sorting string in Descending order C++


The sorting in ascending or descending order, however, can duly be performed by using string sort method and other means too in the C++ programming. But here, the string compare (first words with the second) and copy (copy the first word in a temp variable) method involved in the inner and outer traversing loop to put the words in descending order as following.

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int main(){
   char str[3][20]={"Ajay","Ramesh","Mahesh"};
   char t[20];
   int i, j;
   for(i=1; i<3; i++){
      for(j=1; j<3; j++){
         if(strcmp(str[j-1], str[j])>0){
               strcpy(t, str[j-1]);
               strcpy(str[j-1], str[j]);
               strcpy(str[j], t);
         }
      }
   }
   cout<<"Sorted in Descending Order ::";
   for(i=3; i>=0; i--){
      cout<<" ";
      cout<<str[i]<<"\n";
   }
   return 0;
}

Output

This program yields the results by sorting the string in descending order after accepting three words (Ajay, Ramesh, and Mahesh) as an input as following;

Sorted in Descending Order::
Ramesh
Mahesh
Ajay

Updated on: 23-Dec-2019

534 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements