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

การเรียงสตริงแบบ Alphanumeric (Dictionary Order)

บทนำ

รายการสตริงที่กำหนดจะถูกเรียงลำดับตามลำดับ Alphanumeric หรือ Dictionary Order ตัวอย่างคำเหล่านี้: Apple, Book, Aim จะถูกเรียงเป็น Aim, Apple, Book หากมีตัวเลข สามารถวางไว้หน้าสตริงตัวอักษรได้

อินพุตและเอาต์พุต

Input: รายการสตริง: Ball Apple Data Area 517 April Man 506
Output: สตริงหลังเรียง: 506 517 Apple April Area Ball Data Man

อัลกอริทึม

sortStr(strArr, n)
Input: รายการสตริงทั้งหมด, จำนวนอิลิเมนต์
Output: สตริงในลำดับ Alphanumeric ที่เรียงแล้ว

Begin
    for round := 1 to n-1, do
        for i := 0 to n-round, do
            res := compare str[i] และ str[i+1]
            // ไม่ว่าจะเป็น +ve, -ve หรือ 0
            if res > 0, then
                swap str[i] และ str[i+1]
        done
    done
End

ตัวอย่างโค้ด (C++)

#include <iostream>
#define N 8
using namespace std;

void display(int n, string str[]) {
    for (int i = 0; i < n; i++)
        cout << str[i] << " ";  // พิมพ์สตริงจากอาเรย์
    cout << endl;
}

void sortStr(int n, string str[]) {
    int i, round, res;
    for (round = 1; round < n; round++)
        for (i = 0; i < n-round; i++) {
            res = str[i].compare(str[i+1]);
            if (res > 0)
                swap(str[i], str[i+1]);  // swap สตริง
        }
}

main() {
    string str[N] = {"Ball", "Apple", "Data", "Area", "517", "April", "Man", "506"};
    cout << "Strings before sort:" << endl;
    display(N, str);
    sortStr(N, str);
    cout << "Strings after sort:" << endl;
    display(N, str);
}

ผลลัพธ์

Strings before sort: Ball Apple Data Area 517 April Man 506
Strings after sort: 506 517 Apple April Area Ball Data Man