字符串的冒泡排序
本题要求使用冒泡排序法对任意给定的N个字符串按从小到大排序,输出扫描完第K(K<N)遍后的中间结果序列。
输入格式:
输入在第1行中给出N和K(1≤K<N≤100),此后N行,每行包含一个长度不超过10的、仅由小写英文字母组成的非空字符串。
输出格式:
输出冒泡排序法扫描完第K遍后的中间结果序列,每行包含一个字符串。
输入样例:
6 2
best
cat
east
a
free
day
输出样例:
best
a
cat
day
east
free
实现代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void sort(char *a[],int m,int n);
int main(){
int M,N,i=0;
scanf("%d%d\n",&M,&N);
char *a[100],str[11]; //要求所存字符串不超过10,加上'\0'
while(i<M){
gets(str); //get()函数:从输入得到字符串存入str[]中,遇回车输入结束。
a[i]=(char *)malloc(sizeof(char)*(strlen(str)+1)); //get()函数将输入的数据和'\0'存入数组sre[]中,
strcpy(a[i],str); //所以待赋值数组需要多申请一个字节的空间存放'\0'
i++;
}
sort(a,M,N); //冒泡排序
for(int j=0;j<M;j++){
printf("%s\n",a[j]);
}
return 0;
}
void sort(char *a[],int m,int n){ //冒泡排序函数
int flag;
char *temp;
for(int i=1;i<=n;i++){
flag=0;
for(int j=0;j<m-i;j++){
if(strcmp(a[j],a[j+1])>0){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
flag=1;
}
}
if(flag==0){
return;
}
}
}
结果截图: