7-14 字符串排序 (20分)

7-14 字符串排序 (20分)

本题要求编写程序,读入5个字符串,按由小到大的顺序输出。

输入格式:
输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。

输出格式:
按照以下格式输出排序后的结果:

After sorted:
每行一个字符串

输入样例:

red yellow blue green white

输出样例:

After sorted:
blue
green
red
white
yellow

参考代码

#include <stdio.h>
#include <string.h>

#define N 5

void buuble(char str[5][81], int n)
{
	int i, j;
	char buf[81];

	for (i = 0; i < n - 1; ++i)
	{
		for (j = 1; j < n - i; ++j)
		{
			if ( strcmp(str[j], str[j - 1]) < 0 )
			{
				memset(buf, 0, sizeof(buf));
				strcpy(buf, str[j]);
				strcpy(str[j], str[j - 1]);
				strcpy(str[j - 1], buf);
			}
		}
	}
}

int main()
{
	char str[N][81];
	int i = 0; 

	for (i = 0; i < N; ++i)
	{
		scanf("%s", str[i]);
	}

	buuble(str, N);

	printf("After sorted:\n");

	for (i = 0; i < N; ++i)
	{
		printf("%s\n", str[i]);
	}
	

	return 0;
}
发布了131 篇原创文章 · 获赞 7 · 访问量 5778

猜你喜欢

转载自blog.csdn.net/wct3344142/article/details/103832691