使用字符串函数按字母顺序对名称进行排序的 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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短