題目
假定有k個(gè)有序數(shù)組绊诲,每個(gè)數(shù)組中含有n個(gè)元素骇吭,您的任務(wù)是將它們合并為單獨(dú)的一個(gè)有序數(shù)組惑申,該數(shù)組共有kn個(gè)元素候学。設(shè)計(jì)和實(shí)現(xiàn) 一個(gè)有效的分治算法解決k-路合并操作問題藕筋,并分析時(shí)間復(fù)雜度。
算法思想
采用分治法歸并排序梳码,歸并兩個(gè)有序數(shù)組時(shí)間復(fù)雜度為O(n)隐圾,將K個(gè)有序數(shù)組分治歸并時(shí)間復(fù)雜度為O(logk),算法整體時(shí)間復(fù)雜度為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;
}