Skip to content

Instantly share code, notes, and snippets.

@aaani
Last active December 19, 2015 17:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaani/5989346 to your computer and use it in GitHub Desktop.
Save aaani/5989346 to your computer and use it in GitHub Desktop.
Here is an implementation for N-way merge using priority queue data structure. Code requires n sorted vector<int> as input and generates one huge vector containing the result of merge of input vectors. The worst case time complexity of this algorithm is O(m * log(m)) where m is the total number of elements in all the lists.
// MergeK
//
// Created by Anirvana Mishra on 6/18/13.
// Copyright (c) 2013 Anirvana Mishra. All rights reserved.
//
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct node{
int value;
int array;
};
node getaNode(int value, int array){
node *aNode=new node();
aNode->value=value;
aNode->array=array;
return *aNode;
}
class compareValue {
public:
bool operator()(node& n1, node& n2)
{
return n1.value>n2.value;
}
};
vector<int> mergeK(vector<int> lists[], int n){
priority_queue<node, vector<node>, compareValue> pq;
vector<int> result;
vector<int> pointers(n,0);
node least;
for(int i=0;i<n;i++){
pq.push(getaNode(lists[i][0], i));
}
while(!pq.empty()){
least=pq.top();
result.push_back(least.value);
pq.pop();
if(pointers[least.array]>=lists[least.array].size()-1) continue;
pointers[least.array]++;
pq.push(getaNode(lists[least.array][pointers[least.array]], least.array));
}
return result;
}
int main(int argc, const char * argv[]) //Driver
{
vector<int> lists[3];
lists[0].push_back(5);
lists[0].push_back(7);
lists[0].push_back(19);
lists[1].push_back(10);
lists[1].push_back(11);
lists[2].push_back(0);
lists[2].push_back(5);
lists[2].push_back(15);
vector<int> result = mergeK(lists, 3);
for(int i=0;i<result.size();i++){
cout<<result[i]<<" ";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment