这是我使用 c++ stl 的代码
#include<iostream>
#include<vector>
#include<climits>
#include<queue>
#define ROWS 4
#define COLS 8
using namespace std;
struct node
{
int ele;
int arr_no;
int next_index;
};
void printVector(vector<int> v)
{
for(unsigned int i=0;i<v.size();i++)
cout<<v[i]<<" ";
}
// THIS IS THE BASIS ON WHICH THE ELEMENTS OF A PRIORITY QUEUE ARE SORTED AND
// KEPT IN THE QUEUE, HERE THE CRITERIA IS THAT THE NODE WITH SMALLER ELEMENT SHOULD
// COME ABOVE THE ONE WITH LARGER ELEMENT
class compare
{
public:
bool operator()(node& n1, node& n2)
{
if (n1.ele > n2.ele)
return true;
else
return false;
}
};
vector<int> mergeKArrays(vector< vector<int> > v)
{
int k = v.size(); // NUMBER OF LISTS
int n = v.at(0).size(); //SIZE OF EACH LIST
vector<int> result;
//result.resize( n*k );
priority_queue<node, vector<node>, compare> minHeap;
for (int i = 0; i < k; i++)
{
node temp;
temp.ele = v[i][0]; //STORE THE FIRST ELEMENT
temp.arr_no = i; //INDEX OF ARRAY
temp.next_index = 1; //INDEX OF NEXT ELEMENT TO BE STORED FROM ARRAY
minHeap.push(temp);
}
// NOW ONE BY ONE GET THE MINIMUM ELEMENT FROM MIN
// HEAP AND REPLACE IT WITH NEXT ELEMENT OF ITS ARRAY
for (int count = 0; count < n*k; count++)
{
// GET THE MINIMUM ELEMENT AND STORE IT IN OUTPUT
node min_ele_node = minHeap.top();
minHeap.pop();
result.push_back(min_ele_node.ele);
// FIND THE NEXT ELELEMENT THAT WILL REPLACE CURRENT
// ROOT OF HEAP. THE NEXT ELEMENT BELONGS TO SAME
// ARRAY AS THE CURRENT ROOT.
node new_node;
new_node.arr_no = min_ele_node.arr_no;
if (min_ele_node.next_index < n)
{
new_node.ele = v.at(min_ele_node.arr_no)[min_ele_node.next_index];
new_node.next_index = min_ele_node.next_index + 1;
}
// IF ROOT WAS THE LAST ELEMENT OF ITS ARRAY
else
{
new_node.ele = INT_MAX; //INT_MAX IS FOR INFINITE
}
// REPLACE ROOT WITH NEXT ELEMENT OF ARRAY
minHeap.push(new_node);
}
return result;
}
int main()
{
int arr[ROWS][COLS] =
{
{10, 20, 30, 40, 50, 60, 71, 86},
{15, 25, 35, 45, 60, 69, 77, 78},
{27, 29, 37, 48, 50, 65, 75, 78},
{32, 33, 39, 50, 80, 133, 139, 150},
};
vector< vector<int> > matrix ;
for( int i=0 ; i < ROWS; i++)
{
vector<int> vec;
for(int j=0; j < COLS; j++)
vec.push_back(arr[i][j]);
matrix.push_back(vec);
}
vector<int> result = mergeKArrays(matrix);
printVector(result);
return 0;
}