该程序从用户那里获取 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 个词存储在这个数组中。
然后,使用冒泡排序按字典顺序对数组进行排序并显示在屏幕上。