Open In App

Merge k Sorted Arrays

Last Updated : 23 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given K sorted arrays, merge them and print the sorted output.

Examples:

Input: K = 3, arr = { {1, 3, 5, 7}, {2, 4, 6, 8}, {0, 9, 10, 11}}
Output: 0 1 2 3 4 5 6 7 8 9 10 11 

Input: k = 4, arr = { {1}, {2, 4}, {3, 7, 9, 11}, {13} }
Output: 1 2 3 4 7 9 11 13

Naive - Concatenate all and Sort

Create an output array of size (n * k) and then copy all the elements into the output array followed by sorting. 

Follow the given steps to solve the problem:

  • Create an output array of size n * k. 
  • Traverse all arrays from start to end and insert all the elements in the output array.
  • Sort output and return.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// This function takes a vector of vectors as an argument and
// All arrays are assumed to be sorted. It merges them
// together and returns the final sorted output.
vector<int> mergeKArrays(const vector<vector<int>>& arr) {
    vector<int> res;

    // Append all arrays into res
    for (const auto& vec : arr) {
        for (int val : vec)
            res.push_back(val);
    }

    // Sort the res
    sort(res.begin(), res.end());

    return res;
}

// Driver's code
int main() {
    vector<vector<int>> arr = { { 2, 6, 12, 34 },
                                { 1, 9, 20, 1000 },
                                { 23, 34, 90, 2000 } };
    vector<int> res = mergeKArrays(arr);

    // Print the array elements
    for (int val : res) {
        cout << val << " ";
    }

    return 0;
}
Java
// Java program to merge K sorted arrays of size N each.

import java.io.*;
import java.util.*;

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.
    public static void mergeKArrays(int[][] arr, int a,
                                    int[] output)
    {
        int c = 0;

        // traverse the matrix
        for (int i = 0; i < a; i++) {
            for (int j = 0; j < 4; j++)
                output[c++] = arr[i][j];
        }

        // sort the array
        Arrays.sort(output);
    }

    // A utility function to print array elements
    public static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
    }

    // Driver's code
    public static void main(String[] args)
    {
        int[][] arr = { { 2, 6, 12, 34 },
                        { 1, 9, 20, 1000 },
                        { 23, 34, 90, 2000 } };
        int K = 4;
        int N = 3;
        int[] output = new int[N * K];

        // Function call
        mergeKArrays(arr, N, output);

        System.out.println("Merged array is ");
        printArray(output, N * K);
    }
}
Python
# Python3 program to merge k sorted arrays of size n each.

# 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.


def mergeKArrays(arr, a, output):
    c = 0

    # traverse the matrix
    for i in range(a):
        for j in range(4):
            output[c] = arr[i][j]
            c += 1

    # sort the array
    output.sort()

# A utility function to print array elements


def printArray(arr, size):
    for i in range(size):
        print(arr[i], end=" ")


# Driver's code
if __name__ == '__main__':
    arr = [[2, 6, 12, 34], [1, 9, 20, 1000], [23, 34, 90, 2000]]
    K = 4
    N = 3
    output = [0 for i in range(N * K)]

    # Function call
    mergeKArrays(arr, N, output)

    print("Merged array is ")
    printArray(output, N * K)

# This code is contributed by umadevi9616
C#
// C# program to merge K sorted arrays of size n each.
using System;
public 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 readonly sorted output.
    public static void mergeKArrays(int[, ] arr, int a,
                                    int[] output)
    {
        int c = 0;

        // traverse the matrix
        for (int i = 0; i < a; i++) {
            for (int j = 0; j < 4; j++)
                output[c++] = arr[i, j];
        }

        // sort the array
        Array.Sort(output);
    }

    // A utility function to print array elements
    public static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
    }

    // Driver's code
    public static void Main(String[] args)
    {
        int[, ] arr = { { 2, 6, 12, 34 },
                        { 1, 9, 20, 1000 },
                        { 23, 34, 90, 2000 } };
        int K = 4;
        int N = 3;
        int[] output = new int[N * K];

        // Function call
        mergeKArrays(arr, N, output);
        Console.WriteLine("Merged array is ");
        printArray(output, N * K);
    }
}

// This code is contributed by Rajput-Ji
JavaScript
// Javascript program to merge k sorted 
// arrays of size n each.

    // 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.
    function mergeKArrays(arr , a,  output)
    {
        var c = 0;

        // traverse the matrix
        for (i = 0; i < a; i++) {
            for (j = 0; j < 4; j++)
                output[c++] = arr[i][j];
        }

        // sort the array
        output.sort((a,b)=>a-b);
    }

    // A utility function to print array elements
    function printArray(arr , size) {
        for (i = 0; i < size; i++)
            document.write(arr[i] + " ");
    }

    // Driver program to test above functions
    
        var arr = [ [ 2, 6, 12, 34 ], 
                    [ 1, 9, 20, 1000 ], 
                    [ 23, 34, 90, 2000 ] ];
        var K = 4;
        var N = 3;
        var output = Array(N * K).fill(0);

        mergeKArrays(arr, N, output);

        document.write("Merged array is ");
        printArray(output, N * K);


// This code contributed by Rajput-Ji

Output
1 2 6 9 12 20 23 34 34 90 1000 2000 

Time Complexity: O(N Log N) where N is the total number of elements in all arrays.
Auxiliary Space O(N) for the output array

Using Merge Sort - Works Better for Equal Sized Arrays

The process begins with merging arrays into groups of two. After the first merge, there will be K/2 arrays remaining. Again merge arrays in groups, now K/4 arrays will be remaining. This is mainly merge sort., Here instead of sorting elements, we sort arrays. Divide K arrays into two halves containing an equal number of arrays until there are two arrays in a group. This is followed by merging the arrays in a bottom-up manner. 

Follow the given steps to solve the problem:

  • Create a recursive function that takes k arrays and returns the output array.
  • In the recursive function, if the value of K is 1 then return the array else if the value of k is 2 then merge the two arrays in linear time and return the array.
  • If the value of k is greater than 2 then divide the group of k elements into two equal halves and recursively call the function, i.e 0 to k/2 array in one recursive function and k/2 to k array in another recursive function.
  • Print the output array.

Below is the implementation of the above approach:

C++14
#include <bits/stdc++.h>
using namespace std;

// Merge a and b into c
void mergeArrays(vector<int>& a, vector<int>& b, 
                                 vector<int>& c) {
    int i = 0, j = 0, k = 0;
    int n1 = a.size();
    int n2 = b.size();
    c.resize(n1 + n2);

    // Traverse both arrays
    while (i < n1 && j < n2) {
        if (a[i] < b[j])
            c[k++] = a[i++];
        else
            c[k++] = b[j++];
    }

    // Store remaining elements of a
    while (i < n1)
        c[k++] = a[i++];

    // Store remaining elements of b
    while (j < n2)
        c[k++] = b[j++];
}

// This function takes a vector of vectors as an argument and
// All arrays are assumed to be sorted. It merges them
// together and returns the final sorted output.
void mergeKArrays(vector<vector<int>>& arr, int lo, int hi,
                                       vector<int>& res) {
  
    // If one array is in range
    if (lo == hi) {
        res = arr[lo];
        return;
    }

    // If only two arrays are left, merge them
    if (hi - lo == 1) {
        mergeArrays(arr[lo], arr[hi], res);
        return;
    }

    // Calculate mid point
    int mid = (lo + hi) / 2;

    // Divide the array into halves
     // Output arrays
    vector<int> out1, out2;
    mergeKArrays(arr, lo, mid, out1);
    mergeKArrays(arr, mid + 1, hi, out2);

    // Merge the output arrays
    mergeArrays(out1, out2, res);
}

// Driver's code
int main() {
    vector<vector<int>> arr = { { 2, 6, 12, 34 },
                                { 1, 9, 20, 1000 },
                                { 23, 34, 90, 2000 } };

    vector<int> res;
    mergeKArrays(arr, 0, arr.size() - 1, res);
  
    for (int val : res)
        cout << val << " ";
    cout << endl;

    return 0;
}
Java
// Java program to merge K sorted arrays of size n each.
import java.util.*;

class GFG {
    static final int N = 4;

    // Merge arr1[0..n1-1] and arr2[0..n2-1] into
    // arr3[0..n1+n2-1]
    static void mergeArrays(int arr1[], int arr2[], int N1,
                            int N2, int arr3[])
    {
        int i = 0, j = 0, k = 0;

        // Traverse both array
        while (i < N1 && j < N2) {
            // Check if current element of first
            // array is smaller than current element
            // of second array. If yes, store first
            // array element and increment first array
            // index. Otherwise do same with second array
            if (arr1[i] < arr2[j])
                arr3[k++] = arr1[i++];
            else
                arr3[k++] = arr2[j++];
        }

        // Store remaining elements of first array
        while (i < N1)
            arr3[k++] = arr1[i++];

        // Store remaining elements of second array
        while (j < N2)
            arr3[k++] = arr2[j++];
    }

    // A utility function to print array elements
    static void printArray(int arr[], int size)
    {
        for (int i = 0; i < size; i++)
            System.out.print(arr[i] + " ");
    }

    // 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 void mergeKArrays(int arr[][], int i, int j,
                             int output[])
    {
        // if one array is in range
        if (i == j) {
            for (int p = 0; p < N; p++)
                output[p] = arr[i][p];
            return;
        }

        // if only two arrays are left them merge them
        if (j - i == 1) {
            mergeArrays(arr[i], arr[j], N, N, output);
            return;
        }

        // output arrays
        int[] out1 = new int[N * (((i + j) / 2) - i + 1)];
        int[] out2 = new int[N * (j - ((i + j) / 2))];

        // divide the array into halves
        mergeKArrays(arr, i, (i + j) / 2, out1);
        mergeKArrays(arr, (i + j) / 2 + 1, j, out2);

        // merge the output array
        mergeArrays(out1, out2, N * (((i + j) / 2) - i + 1),
                    N * (j - ((i + j) / 2)), output);
    }

    // Driver's code
    public static void main(String[] args)
    {

        // Change n at the top to change number of elements
        // in an array
        int arr[][] = { { 2, 6, 12, 34 },
                        { 1, 9, 20, 1000 },
                        { 23, 34, 90, 2000 } };

        int K = arr.length;
        int[] output = new int[N * K];

        // Function call
        mergeKArrays(arr, 0, 2, output);

        System.out.print("Merged array is "
                         + "\n");
        printArray(output, N * K);
    }
}

// This code is contributed by gauravrajput1
Python
# Python program to merge K
# sorted arrays of size n each.
N = 4

# Merge arr1[0..n1-1] and arr2[0..n2-1] into
# arr3[0..n1+n2-1]


def mergeArrays(arr1, arr2, N1, N2, arr3):

    i, j, k = 0, 0, 0

    # Traverse both array
    while (i < N1 and j < N2):

        # Check if current element of first
        # array is smaller than current element
        # of second array. If yes, store first
        # array element and increment first array
        # index. Otherwise do same with second array
        if (arr1[i] < arr2[j]):
            arr3[k] = arr1[i]
            k += 1
            i += 1
        else:
            arr3[k] = arr2[j]
            k += 1
            j += 1

    # Store remaining elements of first array
    while (i < N1):
        arr3[k] = arr1[i]
        k += 1
        i += 1

    # Store remaining elements of second array
    while (j < N2):
        arr3[k] = arr2[j]
        k += 1
        j += 1

# A utility function to print array elements


def printArray(arr, size):

    for i in range(size):
        print(arr[i], end=" ")

# 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.


def mergeKArrays(arr, i, j, output):

    global N

    # If one array is in range
    if (i == j):
        for p in range(N):
            output[p] = arr[i][p]

        return

    # If only two arrays are left
    # them merge them
    if (j - i == 1):
        mergeArrays(arr[i], arr[j],
                    N, N, output)
        return

    # Output arrays
    out1 = [0 for i in range(N * (((i + j) // 2) - i + 1))]
    out2 = [0 for i in range(N * (j - ((i + j) // 2)))]

    # Divide the array into halves
    mergeKArrays(arr, i, (i + j) // 2, out1)
    mergeKArrays(arr, (i + j) // 2 + 1, j, out2)

    # Merge the output array
    mergeArrays(out1, out2,
                N * (((i + j) / 2) - i + 1),
                N * (j - ((i + j) / 2)), output)


# Driver's code
if __name__ == '__main__':
    arr = [[2, 6, 12, 34],
           [1, 9, 20, 1000],
           [23, 34, 90, 2000]]

    K = len(arr)
    output = [0 for i in range(N * K)]

    # Function call
    mergeKArrays(arr, 0, 2, output)

    print("Merged array is ")
    printArray(output, N * K)

# This code is contributed by shinjanpatra
C#
// C# program to merge K sorted arrays of size n each.
using System;

class GFG {

    static readonly int N = 4;

    public static int[] GetRow(int[, ] matrix, int row)
    {
        var rowLength = matrix.GetLength(1);
        var rowVector = new int[rowLength];

        for (var i = 0; i < rowLength; i++)
            rowVector[i] = matrix[row, i];

        return rowVector;
    }

    // Merge arr1[0..n1-1] and arr2[0..n2-1] into
    // arr3[0..n1+n2-1]
    static void mergeArrays(int[] arr1, int[] arr2, int N1,
                            int N2, int[] arr3)
    {
        int i = 0, j = 0, k = 0;

        // Traverse both array
        while (i < N1 && j < N2) {

            // Check if current element of first
            // array is smaller than current element
            // of second array. If yes, store first
            // array element and increment first array
            // index. Otherwise do same with second array
            if (arr1[i] < arr2[j])
                arr3[k++] = arr1[i++];
            else
                arr3[k++] = arr2[j++];
        }

        // Store remaining elements of first array
        while (i < N1)
            arr3[k++] = arr1[i++];

        // Store remaining elements of second array
        while (j < N2)
            arr3[k++] = arr2[j++];
    }

    // A utility function to print array elements
    static void printArray(int[] arr, int size)
    {
        for (int i = 0; i < size; i++)
            Console.Write(arr[i] + " ");
    }

    // 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 readonly sorted output.
    static void mergeKArrays(int[, ] arr, int i, int j,
                             int[] output)
    {

        // If one array is in range
        if (i == j) {
            for (int p = 0; p < N; p++)
                output[p] = arr[i, p];

            return;
        }

        // If only two arrays are left them merge them
        if (j - i == 1) {
            mergeArrays(GetRow(arr, i), GetRow(arr, j), N,
                        N, output);
            return;
        }

        // Output arrays
        int[] out1 = new int[N * (((i + j) / 2) - i + 1)];
        int[] out2 = new int[N * (j - ((i + j) / 2))];

        // Divide the array into halves
        mergeKArrays(arr, i, (i + j) / 2, out1);
        mergeKArrays(arr, (i + j) / 2 + 1, j, out2);

        // Merge the output array
        mergeArrays(out1, out2, N * (((i + j) / 2) - i + 1),
                    N * (j - ((i + j) / 2)), output);
    }

    // Driver's code
    public static void Main(String[] args)
    {

        // Change n at the top to change number of elements
        // in an array
        int[, ] arr = { { 2, 6, 12, 34 },
                        { 1, 9, 20, 1000 },
                        { 23, 34, 90, 2000 } };
        int K = arr.GetLength(0);
        int[] output = new int[N * K];

        // Function call
        mergeKArrays(arr, 0, 2, output);

        Console.Write("Merged array is "
                      + "\n");
        printArray(output, N * K);
    }
}

// This code is contributed by Rajput-Ji
JavaScript
// Javascript program to merge k 
// sorted arrays of size n each.
let N =  4

// Merge arr1[0..n1-1] and arr2[0..n2-1] into
// arr3[0..n1+n2-1]
function mergeArrays(arr1, arr2, N1, N2, arr3)
{
    let i = 0, j = 0, k = 0;

    // Traverse both array
    while (i < N1 && j < N2)
    {
        
        // Check if current element of first
        // array is smaller than current element
        // of second array. If yes, store first
        // array element and increment first array
        // index. Otherwise do same with second array
        if (arr1[i] < arr2[j])
            arr3[k++] = arr1[i++];
        else
            arr3[k++] = arr2[j++];
    }
    
    // Store remaining elements of first array
    while (i < N1)
        arr3[k++] = arr1[i++];

    // Store remaining elements of second array
    while (j < N2)
        arr3[k++] = arr2[j++];
}

// A utility function to print array elements
function printArray(arr, size)
{
    for(let i = 0; i < size; i++)
        document.write(arr[i] + " ");
}

// 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.
function mergeKArrays(arr, i, j, output)
{
    
    // If one array is in range
    if (i == j)
    {
        for(let p = 0; p < N; p++)
            output[p] = arr[i][p];
            
        return;
    }
    
    // If only two arrays are left 
    // them merge them
    if (j - i == 1)
    {
        mergeArrays(arr[i], arr[j],
                    N, N, output);
        return;
    }
    
    // Output arrays
    let out1 = new Array(N * (((i + j) / 2) - i + 1))
    let out2 = new Array(N * (j - ((i + j) / 2)));
    
    // Divide the array into halves
    mergeKArrays(arr, i, (i + j) / 2, out1);
    mergeKArrays(arr, (i + j) / 2 + 1, j, out2);
    
    // Merge the output array
    mergeArrays(out1, out2, 
                N * (((i + j) / 2) - i + 1),
                N * (j - ((i + j) / 2)), output);
}

// Driver code

// Change n at the top to change number
// of elements in an array
let arr = [ [ 2, 6, 12, 34 ],
            [ 1, 9, 20, 1000 ],
            [ 23, 34, 90, 2000 ] ];
let K = arr.length;
let output = new Array(N * K);

mergeKArrays(arr, 0, 2, output);

document.write("Merged array is " + "<br>");
printArray(output, N * K);

// This code is contributed by Mayank Tyagi

Output
1 2 6 9 12 20 23 34 34 90 1000 2000 

Time Complexity: For simplicity, we assume that all arrays are of same size n. We get time complexity as O(n* k * log k).  There are log k levels as in each level the K arrays are divided in half and at each level, the k arrays are traversed.
Auxiliary Space: O(n * k)

Using Min-Heap - Works better for Different Sized Arrays

The idea is to use Min Heap. This MinHeap based solution has the same time complexity which is O(N log k). Here N is total number of elements. But for a different and particular sized array, this solution works much better. The process must start with creating a MinHeap and inserting the first element of all the k arrays. Remove the root element of Minheap and put it in the output array and insert the next element from the array of removed element. To get the result the step must continue until there is no element left in the MinHeap. 

Follow the given steps to solve the problem:

  • Create a min Heap and insert the first element of all the K arrays.
  • Run a loop until the size of MinHeap is greater than zero.
    • Remove the top element of the MinHeap and print the element.
    • Now insert the next element from the same array in which the removed element belonged.
    • If the array doesn't have any more elements, then replace root with infinite. After replacing the root, heapify the tree.
  • Return the output array

Please refer Merge k sorted arrays using Min Heap for detailed explanation and implementation.

Time Complexity: O(N log k), Here N is total number of elements in all input arrays.
Auxiliary Space: O(k), If Output is not stored then the only space required is the Min-Heap of K elements.


Next Article

Similar Reads