题目描述
输入一组字符串,用2-路归并排序按字典顺序进行降序排序。
输入
测试次数t
每组测试数据:数据个数n,后跟n个字符串,字符串不含空格。
输出
对每组测试数据,输出2-路归并排序的每一趟排序结果。每组测试数据的输出之间有1空行。
输入样例1
2
6 shenzhen beijing guangzhou futian nanshan baoan
10 apple pear peach grape cherry dew fig haw lemon marc
输出样例1
shenzhen beijing guangzhou futian nanshan baoan
shenzhen guangzhou futian beijing nanshan baoan
shenzhen nanshan guangzhou futian beijing baoan
pear apple peach grape dew cherry haw fig marc lemon
pear peach grape apple haw fig dew cherry marc lemon
pear peach haw grape fig dew cherry apple marc lemon
pear peach marc lemon haw grape fig dew cherry apple
思路总结:
这里使用了vector容器,将字符串数组存放到容器中,然后使用sort函数进行字典序排序。接着设一个times变量,初始值是2,两两合并,合并后一个数组的大小分别是1,2,4,8;若剩下的不够长就剩下的组成一个组,不操作 。当times/2比n大跳出循环。
代码
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int t;
class MergeSort {
private:
int n;
int low, high;
int times = 2;
vector<string> str;
void Merge_Sort(int low, int high);
void Merge(int low, int high);
public:
void main();
};
bool Comp(const string& a, const string& b)
{
return a > b;
}
void MergeSort::Merge(int low, int high)
{
vector<string> tmp;
for (int i = low; i <= high; i++)
{
tmp.push_back(str[i]);
}
sort(tmp.begin(), tmp.end(), Comp);
int k = 0;
for (int i = low; i <= high; i++)
{
str[i] = tmp[k++];
}
}
void MergeSort::Merge_Sort(int low, int high)
{
while (1)
{
if (times / 2 > n)break;
if (times > n && times / 2 <= n)
{
Merge(0, n - 1);
}
if (times < n)
{
for (int i = 0; i < n; i += times)
{
if ((i + times - 1) < n)
Merge(i, i + times - 1);
else
Merge(i, high);
}
}
for (int i = 0; i < n; i++)
{
cout << str[i];
if (i < n - 1)cout << ' ';
}
cout << endl;
times *= 2;
}
}
void MergeSort::main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
string tmpstr;
cin >> tmpstr;
str.push_back(tmpstr);
}
Merge_Sort(0, n - 1);
}
int main()
{
cin >> t;
while (t--)
{
MergeSort ms;
ms.main();
if (t)cout << endl;
}
}