此程序从用户处获取 10 个单词,并按字典顺序对它们进行排序。
在此程序中,我们使用了冒泡排序算法。因此,在继续之前,请访问我们的 冒泡排序算法 教程。
示例:按字典顺序排序单词
#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;
}
输出
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
为了解决此程序,我们创建了一个字符串对象数组 str[10]。
用户输入的 10 个单词存储在此数组中。
然后,使用冒泡排序将数组按字典顺序排序并在屏幕上显示。