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;