/*
输入一串字符,可以是多行,最后以'#'字符结尾
输出的结果是将单词按照ASCII升序输出的
*/
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
void swap(string* pStr[], int first, int second);
void sort(string* pStr[], int start, int end);
int count_words(const string& text, const string& separators);
void extract_words(string* pStr[], const string& text, const string& separators);
void show_words(string* pStr[], int count);
int main()
{
string text;
const string separators = " ,.\n\""; //定义分隔符
cout << endl << "Enter a string terminated by #: " << endl;
std::getline(cin, text, '#');
int word_count = count_words(text, separators);
if (word_count == 0)
{
cout << endl << "No words in text." << endl;
return 0;
}
string** pWords = new string * [word_count];
extract_words(pWords, text, separators);
sort(pWords, 0, word_count - 1);
show_words(pWords, word_count);
return 0;
}
//计算输入的字符串中,一共包含多少个单词
int count_words(const string& text, const string& separators)
{
int count, start, end;
count = 0;
start = text.find_first_not_of(separators);
end = 0;
while (start != string::npos)
{
end = text.find_first_of(separators, start + 1);
if (end == string::npos)
end = text.length();
count++;
start = text.find_first_not_of(separators, end + 1);
}
return count;
}
//将单词分割出来,放入string数组中
void extract_words(string* pStr[], const string& text, const string& separators)
{
int count, start, end;
count = 0;
start = text.find_first_not_of(separators);
end = 0;
while (start != string::npos)
{
end = text.find_first_of(separators, start + 1);
if (end == string::npos)
end = text.length();
pStr[count++] = new string(text.substr(start, end - start));
start = text.find_first_not_of(separators, end + 1);
}
}
//快速排序算法
void sort(string* pStr[], int start, int end)
{
if (start > end)
return;
swap(pStr, start, (start + end) / 2);
int current = start;
for(int i=start+1; i<=end; i++)
if(*(pStr[i]) < *(pStr[start]))
swap(pStr, ++current, i);
swap(pStr, start, current);
sort(pStr, start, current - 1);
sort(pStr, current + 1, end);
}
//交换两个位置的数据
void swap(string* pStr[], int first, int second)
{
string* temp = pStr[first];
pStr[first] = pStr[second];
pStr[second] = temp;
}
void show_words(string* pStr[], int count)
{
for (int i = 0; i < count; i++)
cout << " " << *(pStr[i]);
}
** 其实,快速排序算法的核心,就是到分解为两两为一组的小事件,而这每两两一组之间又都满足升序或者降序规则,最后,将两两一组的小事件比较大小,就完成了排序**