排序问题题解大合集
众所周知,字符也是可以排序的
算法1
我们一边读入字符,一边把字符的个数增加:
char a[101];
int n=0;
while(cin>>a[++n]);
排完序后我们输出就可以了
但是——
输出的时候不能等于n
血的教训
所以,我们得出一下代码:
for(int i=1;i<n;i++)cout<<a[i];
参考文献
C++ 代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
char a[101];
int n=0;
while(cin>>a[++n]);
sort(a,a+n);
for(int i=1;i<n;i++)cout<<a[i];
}
算法二
蛋疼的我用了结构体,大家其实可以不用
把字符串的每一项赋值一下,排序输出即可
赋值:
int n=st.size();
for(int i=0;i<n;i++)f[i].ch=st[i];
排序:
struct node{
char ch;
}f[101];
bool cmp(node a,node b){
return a.ch<b.ch;
}
sort(f,f+n,cmp);
输出:
for(int i=0;i<st.size();i++)cout<<f[i].ch;
参考文献
C++ 代码
#include<bits/stdc++.h>
using namespace std;
struct node{
char ch;
}f[101];
bool cmp(node a,node b){
return a.ch<b.ch;
}
int main()
{
string st;
cin>>st;
int n=st.size();
for(int i=0;i<n;i++)f[i].ch=st[i];
sort(f,f+n,cmp);
for(int i=0;i<n;i++)cout<<f[i].ch;
}