Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ sắp xếp phần tử theo thứ tự từ điển


Thứ tự từ điển (Lexicographical order) là cách sắp xếp từ dựa trên thứ tự bảng chữ cái theo chữ cái. Ví dụ:

Danh sách từ: Harry Adam Sam Thứ tự từ điển: Adam Harry Sam

Chương trình sắp xếp theo thứ tự từ điển:

Ví dụ

#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; }

Kết quả

Kết quả chương trình trên:

Enter the elements... Orange Grapes Mango Apple Guava The elements in lexicographical order are... Apple Grapes Guava Mango Orange

Trong chương trình, mảng chuỗi s[] được định nghĩa và người dùng nhập phần tử:

string s[5], temp; cout<<"Enter the elements..."<<endl; for(i = 0; i < 5; ++i) getline(cin, s[i]);

Các phần tử sắp xếp theo bảng chữ cái bằng vòng lặp lồng nhau:

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

Cuối cùng hiển thị tất cả phần tử theo thứ tự từ điển:

cout << "The elements in lexicographical order are... " << endl; for(int i = 0; i < 5; ++i) cout << s[i] << endl;