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