字符串排序
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
输入3个字符串,按字典序从小到大进行排序。
Input
输入数据有一行,分别为3个字符串,用空格分隔,每个字符串长度不超过100。
Output
输出排序后的三个字符串,用空格分隔。
Sample Input
abcd cdef bcde
Sample Output
abcd bcde cdef
#include<stdio.h>
#include<math.h>
#include<string.h>
int main()
{
int i, j;
char a[3][110];
char t[110];
memset(a, 0, sizeof(a));
memset(t, 0, sizeof(t));
for(i = 0; i < 3; i++)
{
scanf("%s", a[i]);
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3 - 1 - i; j++)//此处若写 j < 3会越界!!!a[3]是非法区域
{//冒泡排序的改进:内层循环为n - 1 - i
//因为每一次内层循环结束都会把最值排在后面,这样可以有效减少循环次数
if(strcmp(a[j], a[j + 1]) > 0)
{
strcpy(t, a[j]);
strcpy(a[j], a[j + 1]);
strcpy(a[j + 1], t);
}//字符串的交换需要用字符串的复制函数
}
}
for(i = 0; i < 3; i++)
{
if(i == 0) printf("%s", a[i]);
else printf(" %s", a[i]);
}
return 0;
}