假定有k个有序数组,每个数组中含有n个元素,您的任务是将它们合并为单独的一个有序数组,该数组共有kn个元素。
设计和实现 一个有效的分治算法解决k-路合并操作问题,并分析时间复杂度。
思路
分治算法即将有序数组两两归并
相关归并代码源自网上博主写的java代码,java的数组可以直接求length,但C++的数组要手动传入length很麻烦……故改写成C++费了一些时间
#include <iostream>
#define N 5
#define INDEX_COUNT 5
using namespace std;
int INDEX[INDEX_COUNT][N] =
{ 1,4,5,8,9,
2,6,8,9,10,
3,5,5,7,8,
4,5,6,7,12,
1,5,8,9,10 };
int MERGED_INDEXS[N*INDEX_COUNT];
void showArray(int a[], int length)
{
for (int i = 0; i < length; i++)
{
cout << a[i] << " ";
}
cout << "\n";
}
int* mergeTwoArrays(int* A, int* B,int lengthA,int lengthB) {
int* temp = new int[lengthA + lengthB];
int index = 0, i = 0, j = 0;
while (i < lengthA && j < lengthB) {
if (A[i] < B[j]) {
temp[index++] = A[i++];
}
else {
temp[index++] = B[j++];
}
}
while (i < lengthA) {
temp[index++] = A[i++];
}
while (j < lengthB) {
temp[index++] = B[j++];
}
return temp;
}
// 分治递归深度为O(log k), 每层合并时间复杂度O(n)
int* kMergeSort(int arrays[INDEX_COUNT][N], int start, int end) {
if (start >= end) {
return arrays[start];
}
int mid = start + (end - start) / 2;
int* left = kMergeSort(arrays, start, mid);
int* right = kMergeSort(arrays, mid + 1, end);
cout << "归并INDEX" << start << "和INDEX" << end<<endl;
return mergeTwoArrays(left, right, N*(mid - start + 1), N*(end - mid));
}
int* mergekSortedArrays(int arrays[INDEX_COUNT][N],int length) {
int* list = new int[N*INDEX_COUNT];
if (arrays == NULL) {
return list;
}
int* ans = kMergeSort(arrays, 0, length - 1);
showArray(ans, N*INDEX_COUNT);
return list;
}
int main(void) {
for (int i = 0; i < INDEX_COUNT; i++) {
cout << "数组" << i << ":";
showArray(INDEX[i], N);
}
mergekSortedArrays(INDEX, INDEX_COUNT);
//showArray(mergeTwoArrays(INDEX[0], INDEX[1], N, N), N + N);
system("pause");
return 0;
}