您的位置:首页 > 其它

合并K个有序数组(假设每个数组长度相等)

2016-12-30 16:40 232 查看
直接上代码,看注释

#include <iostream>
using namespace std;

struct HeapNode {
int val;//num value
int i;//array index
int j;//num index
};

//length of each array
static const int numLen = 3;

//adjust minheap
void MinHeapFixDown(HeapNode data[], int i, const int len) {
HeapNode tmp = data[i];
int j = 2*i+1;
while (j < len) {
if (j+1 < len && data[j+1].val < data[j].val)
++j;
if (data[j].val >= tmp.val)
break;
data[i] = data[j];
i = j;
j = 2*i+1;
}
data[i] = tmp;
}

//Create Min Heap
void MakeMinHeap(HeapNode data[], const int len) {
for (int i = len/2-1; i >= 0; --i)
MinHeapFixDown(data, i, len);
}

//Merge Array
void MergeArray(int nums[][numLen], const int k, int res[]) {
//temp array used to store nodes
HeapNode tmp[k];
//initialize the tmp by the first element of each array
for (int i = 0; i < k; ++i){
tmp[i].val = nums[i][0];
tmp[i].i = i;
tmp[i].j = 0;
}
//Create the heap
MakeMinHeap(tmp, k);
int count = 0; //count the number of arrays been merged
int index = 0; //result array index
//until all the arrays been merged
while (count != k) {
//the first element of the array is the minimum
res[index++] = tmp[0].val;
//if not walk to the end of one array
if (tmp[0].j != numLen-1) {
//update the the node into the next node in the ith array
tmp[0].j = tmp[0].j+1;
tmp[0].val = nums[tmp[0].i][tmp[0].j];
//adjust the heap
MinHeapFixDown(tmp, 0, k-count);
}
//if walk to the end of one array
else {
//count plus one
++count;
//assign the first node with the last node
tmp[0] = tmp[k-count];
//adjust the heap
//Note::len is k-count
MinHeapFixDown(tmp, 0, k-count);
}
}
}

int main() {
const int row = 6;
int nums[row][numLen] = {{22,112,210},{2,5,12},{6,9,13},{7,8,10},{3,11,28},{13,14,15}};
int res[row*numLen];
MergeArray(nums, row, res);
for (int i = 0 ; i < row*numLen; ++i)
cout<<res[i]<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: