// define max value for min heap when array doesn't have any more element
public static final int MAX_VALUE = 10000;
static int[] mergeKArray(int a[][], int row, int col){
int count = 0;
if(row == 0 || row == 1) return a[0];
// declare final merged sorted array
int mergeArr[] = new int[row*col];
// allocation of heapNode array which has size no of row times.
heapNode[] hn = new heapNode[row];
for (int i = 0; i<row; i++)
{
hn[i] = new heapNode(a[i][0], 1, i);
//hn[i].key = a[i][0];
//hn[i].index = 1;
//hn[i].n = i;
}
// convert heapNode array to minheap
minHeap(hn);
heapNode minKeyNode;
for(int i = 0; i< row*col; i++)
{
minKeyNode = minValueHeap(hn);
mergeArr[count++] = minKeyNode.key;
if(minKeyNode.index < a[minKeyNode.n].length)
{
minKeyNode.key = a[minKeyNode.n][minKeyNode.index];
minKeyNode.index++;
}else minKeyNode.key = MAX_VALUE;
hn[0] = minKeyNode;
minHeapify(hn, 0, row);
}
return mergeArr;
}
private static void minHeap(heapNode[] hn) {
int n = hn.length;
if(n == 0 || n == 1) return;
for(int i=n/2; i>=0; i--)
{
minHeapify(hn,i,n);
}
}
private static void minHeapify(heapNode[] hn, int i, int n){
int minIndex = i;
int l = left(i);
int r = right(i);
if(l < n && (hn[l].key < hn[i].key))
{
minIndex = l;
}
if(r < n && (hn[minIndex].key > hn[r].key))
{
minIndex = r;
}
if(minIndex != i)
{
swap(hn, minIndex, i);
minHeapify(hn, minIndex, n);
}
}
private static void swap(heapNode hn[], int minIndex, int i){
heapNode tmp = hn[i];
hn[i] = hn[minIndex];
hn[minIndex] = tmp;
}
private static heapNode minValueHeap(heapNode hn[]){
return hn[0];
}
private static int right(int i) {
return 2*i+2;
}
private static int left(int i) {
return 2*i+1;
}
References:
http://www.geeksforgeeks.org/merge-k-sorted-arrays/