使用字符串函数按字母顺序对名称进行排序的 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 他舅生日祝福语简短