輸入 10 位學生姓名與成績,依姓名字典序排序輸出,姓名與成績對應關係保持不變。
輸入: Bush White Mark Jean Black Wood Jenny Frank Bill Smith 78 85 96 65 46 83 77 88 54 98 輸出: Bill,54 Black,46 Bush,78 Frank,88 Jean,65 Jenny,77 Mark,96 Smith,98 White,85 Wood,83
#include <stdio.h>
#include <string.h>
int main() {
char name[10][120], tmpName[120];
int score[10], tmpScore;
// 讀取 10 個姓名
for (int i = 0; i < 10; ++i) gets(name[i]);
// 讀取 10 個成績
for (int i = 0; i < 10; ++i) scanf("%d", &score[i]);
// 氣泡排序(同步交換姓名與成績)
for (int i = 0; i < 9; ++i) {
for (int j = 0; j < 9 - i; ++j) {
if (strcmp(name[j], name[j+1]) > 0) {
strcpy(tmpName, name[j]);
strcpy(name[j], name[j+1]);
strcpy(name[j+1], tmpName);
tmpScore = score[j];
score[j] = score[j+1];
score[j+1] = tmpScore;
}
}
}
for (int i = 0; i < 10; ++i)
printf("%s,%d\n", name[i], score[i]);
return 0;
}
strcmp 比較字串字典序。姓名,成績,每行一筆。