## subject

Suppose there are k ordered arrays, each of which contains n elements. Your task is to merge them into a single ordered array, which has kn elements in total. Design and implement an effective divide and conquer algorithm to solve the k-path merge operation problem, and analyze the time complexity.

## Algorithmic thought

The time complexity of merging two ordered arrays is O(n), the time complexity of merging K ordered arrays is O(logk), the overall time complexity of the algorithm is O(nlogk), and vector container is used in the program.

``````#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;
}
``````