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

โปรแกรม C++ เรียงลำดับ Lexicographical (Dictionary Order)

Lexicographical Order = เรียงตามตัวอักษรพจนานุกรม (A-Z, 0-9)

ตัวอย่าง: Harry, Adam, Sam → Adam, Harry, Sam

โค้ดโปรแกรม (Bubble Sort)

#include <iostream>
#include <string>
using namespace std;

int main() {
    string s[5], temp;
    cout << "Enter 5 strings:\n";
    for (int i = 0; i < 5; ++i)
        getline(cin, s[i]);
    
    // Bubble Sort
    for (int i = 0; i < 4; ++i)
        for (int j = i + 1; j < 5; ++j)
            if (s[i] > s[j]) {
                temp = s[i];
                s[i] = s[j];
                s[j] = temp;
            }
    
    cout << "\nLexicographical Order:\n";
    for (int i = 0; i < 5; ++i)
        cout << s[i] << endl;
    return 0;
}

ผลลัพธ์

Enter 5 strings:
Orange
Grapes
Mango
Apple
Guava

Lexicographical Order:
Apple
Grapes
Guava
Mango
Orange

C++ Modern (STL Sort)

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main() {
    vector<string> v = {"Orange", "Grapes", "Mango", "Apple", "Guava"};
    sort(v.begin(), v.end());  // Default: Lexicographical (operator<)
    
    for (const auto& s : v)
        cout << s << endl;
    return 0;
}

Custom Comparator

// Case-insensitive
sort(v.begin(), v.end(), [](const string& a, const string& b) {
    return strcasecmp(a.c_str(), b.c_str()) < 0;
});

// Descending
sort(v.begin(), v.end(), greater<>());

std::sort ใช้ Introsort (O(n log n)) เร็วกว่า Bubble Sort (O(n²)) มาก