题目
假定有k个有序数组,每个数组中含有n个元素,您的任务是将它们合并为单独的一个有序数组,该数组共有kn个元素。设计和实现 一个有效的分治算法解决k-路合并操作问题,并分析时间复杂度。
算法思想
采用分治法归并排序,归并两个有序数组时间复杂度为O(n),将K个有序数组分治归并时间复杂度为O(logk),算法整体时间复杂度为O(nlogk),程序里用到了vector向量容器。
#include <iostream>
#include <vector>
using namespace std;
vector<int> mergeTowArrays(vector<int>A,vector<int>B)
{
vector<int>temp;
temp.resize(A.size() + B.size());
int index = 0, j = 0, i = 0;
while (i < A.size() && j < B.size())
{
if (A[i] < B[j])
temp[index++] = A[i++];
else
temp[index++] = B[j++];
}
while (i < A.size())
temp[index++] = A[i++];
while (j < B.size())
temp[index++] = B[j++];
return temp;
}
vector<int> kMergeSort(vector<vector<int>>A, int start, int end)
{
if (start >= end)
return A[start];
int mid = start + (end - start) / 2;
vector<int>Left = kMergeSort(A, start, mid);
vector<int>Right = kMergeSort(A, mid + 1, end);
return mergeTowArrays(Left, Right);
}
vector<int> mergeSortArrays(vector <vector<int>>A)
{
vector<int>temp;
if (A.empty() || A.size() == 0 || A[0].size() == 0)
return temp;
temp = kMergeSort(A, 0, A.size() - 1);
return temp;
}
int main(void)
{
int k,n;
cin >> k >> n;
vector<vector<int>>A(k);
for (int i = 0; i < k; i++)
{
A[i].resize(n);
}
for (int i = 0; i < A.size(); i++)
{
for (int j = 0; j < A[0].size(); j++)
cin >> A[i][j];
}
vector<int>result;
result = mergeSortArrays(A);
for (int i = 0; i < result.size(); i++)
{
cout << result[i] << " ";
}
cout << endl;
system("pause");
return 0;
}