C++ Program to Sort Elements in Lexicographical Order (Dictionary Order)

#include <iostream>
using namespace std;
int main() {
   int i,j;
   string s[5], temp;
   cout<<"Enter the elements..."<<endl;
   for(i = 0; i < 5; ++i)
   getline(cin, s[i]);
   for(i = 0; i < 4; ++i)
   for(j = i+1; j < 5; ++j) {
      if(s[i] > s[j]) {
         temp = s[i];
         s[i] = s[j];
         s[j] = temp;
      }
   }
   cout << "The elements in lexicographical order are... " << endl;
   for(int i = 0; i < 5; ++i)
   cout << s[i] << endl;
   return 0;
}

OUTPUT:

Enter the elements…
Orange
Grapes
Mango
Apple
Guava
The elements in lexicographical order are...
Apple
Grapes
Guava
Mango
Orange

Leave a Comment