本题要求编写程序,输入若干英文单词,对这些单词按长度从小到大排序后输出。如果长度相同,按照输入的顺序不变。
输入格式:
输入为若干英文单词,每行一个,以#作为输入结束标志。其中英文单词总数不超过20个,英文单词为长度小于10的仅由小写英文字母组成的字符串。
输出格式:
输出为排序后的结果,每个单词后面都额外输出一个空格。
输入样例:
blue
red
yellow
green
purple
输出样例:
red blue green yellow purple
方法1:
用二维数组存储单词,然后排序,输出
#include<stdio.h>
#include<string.h>
int main()
{
char words[21][10],t[10];
int cnt=0;
gets(t);
while(t[0]!='#'){
strcpy(words[cnt++],t);
gets(t);
}
for(int i=0;i<cnt;i++){ //选择排序
int min=i;
for(int j=i+1;j<cnt;j++){
if(strlen(words[j])<strlen(words[min]))
min=j;
}
if(min!=i){
strcpy(t,words[i]);
strcpy(words[i],words[min]);
strcpy(words[min],t);
}
}
for(int i=0;i<cnt;i++) printf("%s ",words[i]);
return 0;
}
用结构体数组存储单词和单词的长度,然后排序
#include<stdio.h>
#include<string.h>
struct words{
char word[10];
int len;
}array[20],temp;
void Sort(int len);
int main()
{
int cnt=0;
gets(temp.word);
while(temp.word[0]!='#'){
strcpy(array[cnt].word,temp.word);
array[cnt].len=strlen(temp.word);
cnt++;
gets(temp.word);
}
Sort(cnt);
for(int i=0;i<cnt;i++) printf("%s ",array[i].word);
return 0;
}
void Sort(int len){
for(int i=0;i<len;i++){
int min_index=i;
for(int j=i+1;j<len;j++){
if(array[j].len<array[min_index].len)
min_index=j;
}
if(min_index!=i){
temp=array[i]; //特别注意,相同的结构体类型可以进行整体操作
array[i]=array[min_index];
array[min_index]=temp;
}
}
}
注:特别要注意的是,相同类型的 结构体,可以进行整体操作,比如,struct student a,b;
那就可以直接让a=b,结果是讲b的每一个成员都赋给了a的成员,两个结构变量的内容是相同的,但是地址还是不同的