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;

更新於: 25-Jun-2020

1 千+次瀏覽

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告