Open In App

Merge k sorted arrays | Set 2 (Different Sized Arrays)

Improve
Improve
Like Article
Like
Save
Share
Report

Given k sorted arrays of possibly different sizes, merge them and print the sorted output.
Examples: 

Input: k = 3 
arr[][] = { {1, 3},
{2, 4, 6},
{0, 9, 10, 11}} ;
Output: 0 1 2 3 4 6 9 10 11
Input: k = 2
arr[][] = { {1, 3, 20},
{2, 4, 6}} ;
Output: 1 2 3 4 6 20

We have discussed a solution that works for all arrays of the same size in Merge k sorted arrays | Set 1.
A simple solution is to create an output array and one by one copy all k arrays to it. Finally, sort the output array. This approach takes O(N Log N) time where N is the count of all elements.
An efficient solution is to use a heap data structure. The time complexity of the heap-based solution is O(N Log k).
1. Create an output array. 
2. Create a min-heap of size k and insert 1st element in all the arrays into the heap 
3. Repeat the following steps while the priority queue is not empty. 
…..a) Remove the minimum element from the heap (minimum is always at the root) and store it in the output array. 
…..b) Insert the next element from the array from which the element is extracted. If the array doesn’t have any more elements, then do nothing.

Below is the implementation of the above approach:

C++




// C++ program to merge k sorted arrays
// of size n each.
#include <bits/stdc++.h>
using namespace std;
 
// A pair of pairs, first element is going to
// store value, second element index of array
// and third element index in the array.
typedef pair<int, pair<int, int> > ppi;
 
// This function takes an array of arrays as an
// argument and all arrays are assumed to be
// sorted. It merges them together and prints
// the final sorted output.
vector<int> mergeKArrays(vector<vector<int> > arr)
{
    vector<int> output;
 
    // Create a min heap with k heap nodes. Every
    // heap node has first element of an array
    priority_queue<ppi, vector<ppi>, greater<ppi> > pq;
 
    for (int i = 0; i < arr.size(); i++)
        pq.push({ arr[i][0], { i, 0 } });
 
    // Now one by one get the minimum element
    // from min heap and replace it with next
    // element of its array
    while (pq.empty() == false) {
        ppi curr = pq.top();
        pq.pop();
 
        // i ==> Array Number
        // j ==> Index in the array number
        int i = curr.second.first;
        int j = curr.second.second;
 
        output.push_back(curr.first);
 
        // The next element belongs to same array as
        // current.
        if (j + 1 < arr[i].size())
            pq.push({ arr[i][j + 1], { i, j + 1 } });
    }
 
    return output;
}
 
// Driver program to test above functions
int main()
{
    // Change n at the top to change number
    // of elements in an array
    vector<vector<int> > arr{ { 2, 6, 12 },
                            { 1, 9 },
                            { 23, 34, 90, 2000 } };
 
    vector<int> output = mergeKArrays(arr);
 
    cout << "Merged array is " << endl;
    for (auto x : output)
        cout << x << " ";
 
    return 0;
}


Java




/*package whatever //do not write package name here */
 
import java.util.ArrayList;
import java.util.PriorityQueue;
 
public class MergeKSortedArrays {
    private static class HeapNode
        implements Comparable<HeapNode> {
        int x;
        int y;
        int value;
 
        HeapNode(int x, int y, int value)
        {
            this.x = x;
            this.y = y;
            this.value = value;
        }
 
        @Override public int compareTo(HeapNode hn)
        {
            if (this.value <= hn.value) {
                return -1;
            }
            else {
                return 1;
            }
        }
    }
 
    // Function to merge k sorted arrays.
    public static ArrayList<Integer>
    mergeKArrays(int[][] arr, int K)
    {
        ArrayList<Integer> result
            = new ArrayList<Integer>();
        PriorityQueue<HeapNode> heap
            = new PriorityQueue<HeapNode>();
 
        // Initially add only first column of elements. First
        // element of every array
        for (int i = 0; i < arr.length; i++) {
            heap.add(new HeapNode(i, 0, arr[i][0]));
        }
 
        HeapNode curr = null;
        while (!heap.isEmpty()) {
            curr = heap.poll();
            result.add(curr.value);
 
            // Check if next element of curr min exists,
            // then add that to heap.
            if (curr.y < (arr[curr.x].length - 1)) {
                heap.add(
                    new HeapNode(curr.x, curr.y + 1,
                                 arr[curr.x][curr.y + 1]));
            }
        }
 
        return result;
    }
 
    public static void main(String[] args)
    {
 
        int[][] arr = { { 2, 6, 12 },
                            { 1, 9 },
                            { 23, 34, 90, 2000 } };
        System.out.println(
            MergeKSortedArrays.mergeKArrays(arr, arr.length)
                .toString());
    }
}
// This code has been contributed by Manjunatha KB


Python3




# Python code to implement the approach
 
import heapq
 
# Merge function merge two arrays
# of different or same length
# if n = max(n1, n2)
# time complexity of merge is (o(n log(n)))
 
# Function for meging k arrays
def mergeK(arr, k):
    res = []
     
    # Declaring min heap
    h = []
     
    # Inserting the first elements of each row
    for i in range(len(arr)):
        heapq.heappush(h, (arr[i][0], i, 0))
         
    # Loop to merge all the arrays
    while h:
       
        # ap stores the row number,
        # vp stores the column number
        val, ap, vp = heapq.heappop(h)
        res.append(val)
        if vp+1 < len(arr[ap]):
            heapq.heappush(h, (arr[ap][vp+1], ap, vp+1))
    return res       
         
 
# Driver code
if __name__ == '__main__':
    arr =[[2, 6, 12 ],
          [ 1, 9 ],
          [23, 34, 90, 2000 ]]
    k = 3
    l = mergeK(arr, k)
    print(*l)


C#




// C# program to merge k sorted arrays
// of size n each.
using System;
using System.Collections.Generic;
class GFG
{
 
    // This function takes an array of arrays as an
    // argument and all arrays are assumed to be
    // sorted. It merges them together and prints
    // the final sorted output.
    static List<int> mergeKArrays(List<List<int>> arr)
    {
        List<int> output = new List<int>();
     
        // Create a min heap with k heap nodes. Every
        // heap node has first element of an array
        List<Tuple<int,Tuple<int,int>>> pq =
        new List<Tuple<int,Tuple<int,int>>>();
     
        for (int i = 0; i < arr.Count; i++)
            pq.Add(new Tuple<int,
                Tuple<int,int>>(arr[i][0],
                                new Tuple<int,int>(i, 0)));
             
        pq.Sort();
     
        // Now one by one get the minimum element
        // from min heap and replace it with next
        // element of its array
        while (pq.Count > 0) {
            Tuple<int,Tuple<int,int>> curr = pq[0];
            pq.RemoveAt(0);
     
            // i ==> Array Number
            // j ==> Index in the array number
            int i = curr.Item2.Item1;
            int j = curr.Item2.Item2;
     
            output.Add(curr.Item1);
     
            // The next element belongs to same array as
            // current.
            if (j + 1 < arr[i].Count)
            {
                pq.Add(new Tuple<int,Tuple<int,int>>(arr[i][j + 1],
                                                    new Tuple<int,int>(i, j + 1)));
                pq.Sort();
            }
        }
        return output;
    }
     
// Driver code
static void Main()
{
     
    // Change n at the top to change number
    // of elements in an array
    List<List<int>> arr = new List<List<int>>();
    arr.Add(new List<int>(new int[]{2, 6, 12}));
    arr.Add(new List<int>(new int[]{1, 9}));
    arr.Add(new List<int>(new int[]{23, 34, 90, 2000}));
 
    List<int> output = mergeKArrays(arr);
 
    Console.WriteLine("Merged array is ");
    foreach(int x in output)
        Console.Write(x + " ");
}
}
 
// This code is contributed by divyeshrabadiya07.


Javascript




// JavaScript code to implement the approach
 
class Node {
constructor(val, row, col) {
this.val = val;
this.row = row;
this.col = col;
}
}
 
class PriorityQueue {
constructor() {
this.items = [];
}
 
 
enqueue(node) {
    let contain = false;
    for (let i = 0; i < this.items.length; i++) {
        if (this.items[i].val > node.val) {
            this.items.splice(i, 0, node);
            contain = true;
            break;
        }
    }
    if (!contain) {
        this.items.push(node);
    }
}
 
dequeue() {
    return this.items.shift();
}
 
isEmpty() {
    return this.items.length == 0;
}
}
 
// Function to merge k arrays
function mergeK(arr, k) {
let res = [];
let pq = new PriorityQueue();
 
 
// Inserting the first elements of each row
for (let i = 0; i < arr.length; i++) {
    pq.enqueue(new Node(arr[i][0], i, 0));
}
 
// Loop to merge all the arrays
while (!pq.isEmpty()) {
    let node = pq.dequeue();
    res.push(node.val);
    if (node.col + 1 < arr[node.row].length) {
        pq.enqueue(new Node(arr[node.row][node.col + 1], node.row, node.col + 1));
    }
}
return res;
}
 
// Driver code
let arr = [[2, 6, 12], [1, 9], [23, 34, 90, 2000]];
let k = 3;
let l = mergeK(arr, k);
document.write(l.join(' '));


Output

Merged array is 
1 2 6 9 12 23 34 90 2000 

Time Complexity: O(N*K*logK)
Auxiliary Space: O(N)



Last Updated : 10 Jul, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads