Algorithm


Step 1: Input
        Read n
          Create vector elements

Step 2: Input Elements
       For i = 1 to n
        Read element
         Add element to elements vector

Step 3: Sort Elements
       Sort elements lexicographically using std::sort

Step 4: Output Sorted Elements
       For each element in elements
        Output element

Code Examples

#1 Code Example- C++ programing Sort Words in Dictionary Order

Code - C++ Programming

#include <iostream>
using namespace std;

int main()
{
    string str[10], temp;

    cout << "Enter 10 words: " << endl;
    for(int i = 0; i < 10; ++i)
    {
      getline(cin, str[i]);
    }

    // Use Bubble Sort to arrange words
    for (int i = 0; i < 9; ++i) {
        for (int j = 0; j < 9 - i; ++j) {
            if (str[j] > str[j + 1]) {
                temp = str[j];
                str[j] = str[j + 1];
                str[j + 1] = temp;
            }
        }
    }

    cout << "In lexicographical order: " << endl;

    for(int i = 0; i < 10; ++i)
    {
       cout << str[i] << endl;
    }
    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter 10 words:
C
C++
Java
Python
Perl
R
Matlab
Ruby
JavaScript
PHP
In lexicographical order:
C
C++
Java
JavaScript
Matlab
PHP
Perl
Python
R
Ruby
Advertisements

Demonstration


C++ Programing Example to Sort Elements in Lexicographical Order (Dictionary Order)-DevsEnv