C ++程序按字典顺序(字典顺序)对元素进行排序
字典顺序表示根据单词的字母顺序在列表中对单词进行排序的方式。例如-
List of words: Harry Adam Sam Lexicographical order of words: Adam Harry Sam
一个按字典顺序对元素进行排序的程序如下-
示例
#include <iostream> using namespace std; int main() { int i,j; string s[5], temp; cout<<"Enter the elements..."<<endl; for(i = 0; i < 5; ++i) getline(cin, s[i]); for(i = 0; i < 4; ++i) for(j = i+1; j < 5; ++j) { if(s[i] > s[j]) { temp = s[i]; s[i] = s[j]; s[j] = temp; } } cout << "The elements in lexicographical order are... " << endl; for(int i = 0; i < 5; ++i) cout << s[i] << endl; return 0; }
输出结果
上面程序的输出如下-
Enter the elements… Orange Grapes Mango Apple Guava The elements in lexicographical order are... Apple Grapes Guava Mango Orange
在上面的程序中,定义了字符串s[],并且用户输入了元素。这在下面给出-
string s[5], temp; cout<<"Enter the elements..."<<endl; for(i = 0; i < 5; ++i) getline(cin, s[i]);
通过使用嵌套的for循环,按字母顺序排列元素。为此的代码片段如下-
for(i = 0; i < 4; ++i) for(j = i+1; j < 5; ++j) { if(s[i] > s[j]) { temp = s[i]; s[i] = s[j]; s[j] = temp; } }
最后,按字典顺序显示所有元素。这在下面给出-
cout << "The elements in lexicographical order are... " << endl; for(int i = 0; i < 5; ++i) cout << s[i] << endl;