题目
本题要求编写程序,输入若干英文单词,对这些单词按长度从小到大排序后输出。如果长度相同,按照输入的顺序不变。
输入格式:
第一行输入一个整数N,代表英文单词的个数,后面输入N行,每行输入一个英文单词.(N不大于
100,每个单词长度也不大于100)
输出格式:
输出为N行,每行代表一个英文单词。
输入样例:
在这里给出一组输入。例如:
5
blue
red
yellow
green
purple
输出样例:
在这里给出相应的输出。例如:
red
blue
green
yellow
purple
题解
#include<iostream>
#include<string.h>
using namespace std;
char s[110][110];
int n;
char temp[110];
int main(){
int n;
cin>>n;
for(int i=0;i<n;i++){
scanf("%s",s[i]);
}
for(int i=0;i<n;i++){
for(int j=0;j<n-i-1;j++){
if(strlen(s[j+1])<strlen(s[j])){
strcpy(temp,s[j]);
strcpy(s[j],s[j+1]);
strcpy(s[j+1],temp);
}
}
}
for(int i=0;i<n;i++){
cout<<s[i];
if(i!=n-1)
puts("");
}
return 0;
}
分析
- 只需要比较长度,用
strlen
字符串的交换用strcpy
- 一个简单的排序算法
for(int i=0;i<n;i++){
for(int j=0;j<n-i-1;j++){