C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

辞書式順序(辞書順)で要素をソートする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;
>
  1. 辞書式順序(辞書順)で要素をソートするJavaプログラム

    この記事では、Javaで配列の要素を辞書式順序で並べ替える方法を理解します。辞書式順序は、辞書のアルファベット順をシーケンスに一般化したものです。 以下は同じのデモンストレーションです- 入力 入力が-であると仮定します Aplha Beta Gamma Delta 出力 必要な出力は-になります Aplha Beta Delta Gamma アルゴリズム Step1- Start Step 2- Declare three integers: I, j, array_length Step 3- Declare a string array Step 4- Prompt th

  2. C++で各対角要素を行列の昇順でソートするプログラム

    n x mの行列Matがあるとすると、このMatを左上から右下に向かって昇順で斜めに並べ替えて、対角線のすべての要素を並べ替える必要があります。したがって、入力行列が-のような場合 3 3 1 1 2 2 1 2 1 1 1 2 出力行列は-になります 1 1 1 1 1 2 2 2 1 2 3 3 これを解決するには、次の手順に従います- Solve()というメソッドを定義します。これには、si、sj、および行列マットが必要です。 n:=行