Vấn đề
Sắp xếp tên do người dùng nhập tại runtime theo thứ tự bảng chữ cái bằng kỹ thuật bubble sort.
Giải pháp
Logic in tên theo thứ tự bảng chữ cái:
for(i = 1; i < ITEMS; i++){
for(j = 1; j <= ITEMS - i; j++){
if(strcmp(string[j-1], string[j]) > 0){
strcpy(dummy, string[j-1]);
strcpy(string[j-1], string[j]);
strcpy(string[j], dummy);
}
}
}
Ví dụ
Chương trình C sắp xếp tên bảng chữ cái dùng hàm chuỗi:
#define ITEMS 5
#define MAXCHAR 20
main(){
char string[ITEMS][MAXCHAR], dummy[MAXCHAR];
int i = 0, j = 0;
printf("Nhap ten %d mon:\n", ITEMS);
while(i < ITEMS)
scanf("%s", string[i++]);
for(i = 1; i < ITEMS; i++){
for(j = 1; j <= ITEMS - i; j++){
if(strcmp(string[j-1], string[j]) > 0){
strcpy(dummy, string[j-1]);
strcpy(string[j-1], string[j]);
strcpy(string[j], dummy);
}
}
}
printf("\nDanh sach sap xep:\n\n");
for(i = 0; i < ITEMS; i++)
printf("%s\n", string[i]);
}
Đầu ra
Kết quả chạy chương trình:
Nhap ten 5 mon: computers architecture organization microprocessor networking Danh sach sap xep: architecture computers microprocessor networking organization