Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C ++ เพื่อจัดเรียงองค์ประกอบตามลำดับศัพท์ (Dictionary Order)


ลำดับพจนานุกรมหมายถึงวิธีการเรียงลำดับคำในรายการ โดยเรียงลำดับตามตัวอักษรตามตัวอักษร ตัวอย่างเช่น −

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(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;