使用字符串函数按字母顺序对名称进行排序的 C 程序。
问题
使用冒泡排序技术按字母顺序对用户在运行时给出的名称进行排序。
解决方案
用于按字母顺序打印名称的逻辑如下-
for (i=1; i < ITEMS; i++){
for (j=1; j <= ITEMS-i ; j++){
if (strcmp (string[j-1], string[j]) > 0){ /* Exchange of contents */
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;
/* Reading the list */
printf ("Enter names of %d items \n ",ITEMS);
while (i < ITEMS)
scanf ("%s", string[i++]);
/* Sorting begins */
for (i=1; i < ITEMS; i++){
for (j=1; j <= ITEMS-i ; j++){
if (strcmp (string[j-1], string[j]) > 0){ /* Exchange of contents */
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]);
}输出结果执行上述程序时,它会产生以下输出-
Enter names of 5 items computers architecture organization microprocessor networking Alphabetical list architecture computers microprocessor networking organization
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特