ปัญหา: เรียงชื่อ (Strings) ตามลำดับตัวอักษร (Alphabetical) ด้วย Bubble Sort
ใช้ strcmp เปรียบเทียบสตริง strcpy สลับค่า
ตรรกะการเรียง
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);
}
}
}
โค้ด C เต็ม
#define ITEMS 5
#define MAXCHAR 20
main() {
char string[ITEMS][MAXCHAR], dummy[MAXCHAR];
int i = 0, j = 0;
printf("Enter names of %d items \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("\nAlphabetical list \n\n");
for (i = 0; i < ITEMS; i++)
printf("%s\n", string[i]);
}
ตัวอย่าง Output
Enter names of 5 items
computers architecture organization microprocessor networking
Alphabetical list
architecture
computers
microprocessor
networking
organization
หมายเหตุ: ใช้ scanf("%s") อ่านได้แค่คำเดียว (ไม่มีช่องว่าง) หากชื่อมีช่องว่าง ต้องใช้ fgets แทน