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

C++ Program to Sort Elements in Dictionary Order

In this example, we will learn to Sort Elements in Lexicographical Order (Dictionary Order).

To understand this example, you should have the knowledge of the following C++ programming topics:


Introduction

This program takes 10 words from the user and sorts them in lexicographical order. We have used the bubble sort algorithm in this program.


Example 1: Program to Sort Words in Dictionary Order

#include <iostream>
using namespace std;

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

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

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

    cout << "\nIn lexicographical order: " << endl;

    for(int i = 0; i < 5; ++i)
    {
       cout << str[i] << endl;
    }
    return 0;
}

Output

Enter 5 words: 
C 
C++
Java
Python
JavaScript

In lexicographical order: 
C
C++
Java
JavaScript
Python

working

To solve this program, an array of string object str[5] is created. The '5' words entered by the user are stored in this array.

Then, the array is sorted in lexicographical order using bubble sort and displayed on the screen.


Next Example

We hope that this Example helped you develop better understanding of the concept of "Sort Elements in Dictionary Order" in C++.

Keep Learning : )

In the next Example, we will learn about C++ Store Information of a Student Using Structure.


- Related Topics