Giới thiệu
Một danh sách các chuỗi cho trước được sắp xếp theo thứ tự alphanumeric (alphanumeric order) hoặc thứ tự từ điển (Dictionary Order). Ví dụ các từ: Apple, Book, Aim, chúng sẽ được sắp xếp thành Aim, Apple, Book. Nếu có một số số, chúng có thể được đặt trước các chuỗi chữ cái.
Đầu vào và Đầu ra
Đầu vào: Danh sách chuỗi: Ball Apple Data Area 517 April Man 506 Đầu ra: Chuỗi sau khi sắp xếp: 506 517 Apple April Area Ball Data Man
Thuật toán
sortStr(strArr, n)
Đầu vào: Danh sách tất cả chuỗi, số lượng phần tử.
Đầu ra: Chuỗi theo thứ tự alphanumeric đã sắp xếp.
Begin
for round := 1 to n-1, do
for i := 0 to n-round, do
res := so sánh str[i] và str[i+1]
// hoặc +ve, hoặc -ve hoặc 0
if res > 0, then
hoán đổi str[i] và str[i+1]
done
done
End
Ví dụ (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] << " "; // in chuỗi từ mảng
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]); // hoán đổi chuỗi
}
}
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);
}
Kết quả
Strings before sort: Ball Apple Data Area 517 April Man 506 Strings after sort: 506 517 Apple April Area Ball Data Man