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

21 Jun, 2022
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++
Java
Python3
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 functionsint 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;}
/*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
# merge function merge two arrays# of different or same length# if n = max(n1, n2)# time complexity of merge is (o(n log(n))) from heapq import merge # function for meging k arraysdef mergeK(arr, k):         l = arr[0]    for i in range(k-1):                 # when k = 0 it merge arr[1]        # with arr[0] here in l arr[0]        # is stored        l = list(merge(l, arr[i + 1]))    return l # for printing arraydef printArray(arr):    print(*arr)  # driver codearr =[[2, 6, 12 ],    [ 1, 9 ],    [23, 34, 90, 2000 ]]k = 3 l = mergeK(arr, k) printArray(l)
// 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 codestatic 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.
Merged array is 
1 2 6 9 12 23 34 90 2000 
Time Complexity: O(N Log k)Auxiliary Space: O(N)
rajutkarshai
divyeshrabadiya07
rajatkumargla19
manjunatha_kb
Code_r
array-merge
cpp-pair
cpp-priority-queue
cpp-vector
priority-queue
Arrays
Heap
Arrays
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.