C语言:国家名称按字母表排序

题目描述

输入一个整数n(n<=20),表示待输入国家的数量。随后输入n个国家或地区的名称 (名称长度为1~30),要求按字母顺序升序输出。

注意:名称中可能包含空格符。

提示

字符串比较请使用函数: int strcmp(const char* str1,const char* str2);

该函数包含在头文件 string.h中。

该函数的返回值:

如果返回值 < 0,则表示 str1 小于 str2。

如果返回值 > 0,则表示 str2 小于 str1。

如果返回值 = 0,则表示 str1 等于 str2。

读入整型数请使用scanf(“%d”,&num)函数,读入之后请用getchar()清除后面的回车符,再读入后面的字符串。

读入一行字符串请使用gets(char *buf)函数。

输入输出格式

输入格式

输入n+1行,第一行为待输入国家的数量,随后的每行包含一个国家或地区的名称,名称可能包含空格符。

输出格式

输出n行,每行包含一个国家或地区的名称,按字母升序输出。

使用冒泡排序

void bubblesort(int n,char arr[n][max+1])
{int i,j;char temp[max+1];for(i=0;i<n-1;i++){for(j=0;j<n-i-1;j++){if(strcmp(arr[j],arr[j+1])>0){strcpy(temp,arr[j]);strcpy(arr[j],arr[j+1]);strcpy(arr[j+1],temp);}}}
}

完整代码

#include <stdio.h>
#include <string.h>
#include <math.h>#define max 30
void bubblesort(int n,char arr[n][max+1])
{int i,j;char temp[max+1];for(i=0;i<n-1;i++){for(j=0;j<n-i-1;j++){if(strcmp(arr[j],arr[j+1])>0){strcpy(temp,arr[j]);strcpy(arr[j],arr[j+1]);strcpy(arr[j+1],temp);}}}
}int main()
{int n;scanf("%d",&n);getchar();char country[n][max+1];int i;for(i=0;i<n;i++){gets(country[i]);}bubblesort(n,country);for(i=0;i<n;i++){printf("%s\n",country[i]);}return 0;
}