Exercise:
Write a C++ program to sort elements into the dictionary order (lexicographical order).
Click Here to View the Solution:
#include <iostream>
using namespace std;
int main()
{
string word[10], temp;
cout << "Insert 10 words: " << endl;
for(int x = 0; x < 10; ++x)
{
getline(cin, word[x]);
}
for (int x = 0; x < 9; ++x)
// Bubble Sort
{
for (int y = 0; y < 9 - x; ++y)
{
if (word[y] > word[y + 1])
{
temp = word[y];
word[y] = word[y + 1];
word[y + 1] = temp;
}
}
}
cout << "\nIn lexicographical order: " << endl;
for(int x = 0; x < 10; ++x)
{
cout << word[x] << endl;
}
return 0;
}
Click Here to View the Output:
Insert 10 words: css vim ruby c# php basic python sql swift java script In lexicographical order: basic c# css java script php python ruby sql swift vim
Click Here to View the Explanation:
- User can arrange a list of words in lexicographical order. 10 words are entered by the user.
- To store the entries of the user, a string object array is created.
- Bubble sort algorithm is used to process the lexicographical order.
- It compared the words 1 by 1 and places them in an alphabetical order.
- The result is displayed on the screen.