我们已经知道了将N个整数按从小到大排序的冒泡排序法。本题要求将此方法用于字符串序列,并对任意给定的K(<N),输出扫描完第K遍后的中间结果序列。
输入格式:
输入在第1行中给出N和K(1≤K<N≤100),此后N行,每行包含一个长度不超过10的、仅由小写英文字母组成的非空字符串。
输出格式:
输出冒泡排序法扫描完第K遍后的中间结果序列,每行包含一个字符串。
输入样例:
6 2
best
cat
east
a
free
day
输出样例:
best
a
cat
day
east
free
可以利用c++里面的string串,因为string相当于一个类,里面重载了<,>,=,==.可以直接把他当成一个int类型的来看。
也可以用c串,比较函数strcmp();复制函数strcpy();
string串代码:
#include<iostream>
#include<string>
using namespace std;
string str[105];
int main(){
int n,m;
string ss;
cin>>n>>m;
for(int i=0;i<n;i++)
cin>>str[i];
for(int i=1;i<=m;i++){
for(int j=0;j<n-i;j++){
if(str[j]>str[j+1]){
ss=str[j];
str[j]=str[j+1];
str[j+1]=ss;
}
}
}
for(int i=0;i<n;i++){
cout<<str[i]<<"\n";
}
return 0;
}
c串代码:
#include <bits/stdc++.h>
using namespace std;
int main()
{
char s[110][20];
int n, m;
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++)
scanf("%s",s[i]);
for(int i = 0; i < m; i++)
{
for(int j = 0; j < n - i - 1; j++)
{
if(strcmp(s[j],s[j+1]) > 0)
{
char t[20];
strcpy(t, s[j]);
strcpy(s[j], s[j+1]);
strcpy(s[j+1], t);
}
}
}
for(int i = 0; i < n; i++)
printf("%s\n",s[i]);
}