Sort Elements in Lexicographical Order in C++



Lexicographical order denotes the way the words are ordered in a list, based on alphabetical order according to their alphabets. For example −

List of words:
Harry
Adam
Sam

Lexicographical order of words:
Adam
Harry
Sam

A program to sort elements in lexicographical order is as follows −

Example

 Live Demo

#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

The output of the above program is as follows −

Enter the elements…
Orange
Grapes
Mango
Apple
Guava

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

In the above program, string s[] is defined and the elements are entered by the user. This is given below −

string s[5], temp;
cout<<"Enter the elements..."<<endl;
for(i = 0; i < 5; ++i)
getline(cin, s[i]);

The elements are arranged alphabetically by using nested for loops. The code snippet for this is as follows −

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

Finally all the elements in lexicographical order are displayed. This is given below −

cout << "The elements in lexicographical order are... " << endl;
for(int i = 0; i < 5; ++i)
cout << s[i] << endl;
Updated on: 2020-06-25T09:08:19+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements