注册 登录
编程论坛 C++教室

[求助]下面的帖子怎么才能改成按使用频率从大到小进行排序

kid1412 发布于 2007-06-27 19:54, 613 次点击

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char *argv[])
{
//select the letters of input the store them in a string
char word;
string str;
while ((word = cin.get()) != '\n'){
if (isalpha(word)){
word = tolower(word);
str += word;
}
}
//insertion sort for the string
for (int i = 1;i < str.size();++i){
if (str[i] < str[i-1]){
char temp = str[i];
int j = i;
do{
str[j] = str[j-1];
--j;
}
while (j > 0 && temp < str[j-1]);
str[j] = temp;
}
}
if (str.empty()){
cerr << "no letter in your input" << endl;
system("pause");
return EXIT_FAILURE;
}
cout << str << endl;
//count the letter times
int pos = 0;
while (true){
char key = str[pos];
int mark = str.find_first_not_of(key,pos);
if (mark == string::npos){
cout << key << "\t\t" << str.size() - pos << endl;
break;
}
int length = mark - pos;
cout << key << "\t\t" << length << endl;
pos = mark;
}
system("PAUSE");
return EXIT_SUCCESS;
}

谢谢拉!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

2 回复
#2
aipb20072007-06-27 20:05
//insertion sort for the string
for (int i = 1;i < str.size();++i){
if (str[i] > str[i-1]){ //change < to >
char temp = str[i];
int j = i;
do{
str[j] = str[j-1];
--j;
}
while (j > 0 && temp < str[j-1]);
str[j] = temp;
}
}

无语,都学到哪里去了?
#3
野比2007-06-27 20:19
遍历.. 先比较再交换...
你用自己的方法试试? 用一个数组保存使用频率, 参考那个统计频率的帖子..
然后根据频率来重排..
1