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
Output1 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
Output1 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.
Similar Reads
Heap Data Structure
A Heap is a complete binary tree data structure that satisfies the heap property: for every node, the value of its children is greater than or equal to its own value. Heaps are usually used to implement priority queues, where the smallest (or largest) element is always at the root of the tree.Basics
2 min read
Introduction to Heap - Data Structure and Algorithm Tutorials
A Heap is a special Tree-based Data Structure that has the following properties.It is a Complete Binary Tree.It either follows max heap or min heap property.Max-Heap: The value of the root node must be the greatest among all its descendant nodes and the same thing must be done for its left and right
15+ min read
Binary Heap
A Binary Heap is a complete binary tree that stores data efficiently, allowing quick access to the maximum or minimum element, depending on the type of heap. It can either be a Min Heap or a Max Heap. In a Min Heap, the key at the root must be the smallest among all the keys in the heap, and this pr
13 min read
Advantages and Disadvantages of Heap
Advantages of Heap Data StructureTime Efficient: Heaps have an average time complexity of O(log n) for inserting and deleting elements, making them efficient for large datasets. We can convert any array to a heap in O(n) time. The most important thing is, we can get the min or max in O(1) timeSpace
2 min read
Time Complexity of building a heap
Consider the following algorithm for building a Heap of an input array A. A quick look over the above implementation suggests that the running time is O(n * lg(n)) since each call to Heapify costs O(lg(n)) and Build-Heap makes O(n) such calls. This upper bound, though correct, is not asymptotically
2 min read
Applications of Heap Data Structure
Heap Data Structure is generally taught with Heapsort. Heapsort algorithm has limited uses because Quicksort is better in practice. Nevertheless, the Heap data structure itself is enormously used. Priority Queues: Heaps are commonly used to implement priority queues, where elements with higher prior
2 min read
Comparison between Heap and Tree
What is Heap? A Heap is a special Tree-based data structure in which the tree is a complete binary tree. Types of Heap Data Structure: Generally, Heaps can be of two types: Max-Heap: In a Max-Heap the key present at the root node must be greatest among the keys present at all of its children. The sa
3 min read
When building a Heap, is the structure of Heap unique?
What is Heap? A heap is a tree based data structure where the tree is a complete binary tree that maintains the property that either the children of a node are less than itself (max heap) or the children are greater than the node (min heap). Properties of Heap: Structural Property: This property sta
4 min read
Easy problems on Heap
Check if a given Binary Tree is a Heap
Given a binary tree, check if it has heap property or not, Binary tree needs to fulfil the following two conditions for being a heap: It should be a complete tree (i.e. Every level of the tree, except possibly the last, is completely filled, and all nodes are as far left as possible.).Every nodeâs v
15+ min read
How to check if a given array represents a Binary Heap?
Given an array, how to check if the given array represents a Binary Max-Heap.Examples: Input: arr[] = {90, 15, 10, 7, 12, 2} Output: True The given array represents below tree 90 / \ 15 10 / \ / 7 12 2 The tree follows max-heap property as every node is greater than all of its descendants. Input: ar
11 min read
Iterative HeapSort
HeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15
11 min read
Find k largest elements in an array
Given an array arr[] and an integer k, the task is to find k largest elements in the given array. Elements in the output array should be in decreasing order.Examples:Input: [1, 23, 12, 9, 30, 2, 50], k = 3Output: [50, 30, 23]Input: [11, 5, 12, 9, 44, 17, 2], k = 2Output: [44, 17]Table of Content[Nai
15+ min read
Kâth Smallest Element in Unsorted Array
Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples:Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content[Naive Ap
15 min read
Height of a complete binary tree (or Heap) with N nodes
Consider a Binary Heap of size N. We need to find the height of it. Examples: Input : N = 6 Output : 2 () / \ () () / \ / () () () Input : N = 9 Output : 3 () / \ () () / \ / \ () () () () / \ () ()Recommended PracticeHeight of HeapTry It! Let the size of the heap be N and the height be h. If we tak
3 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1}Output : arr[] = {10, 5, 3, 1}Input : arr[] = {1, 50, 100, 25}Output : arr[] = {100, 50, 25, 1}Prerequisite: Heap sort using min heap.Using Min Heap Implementation - O(n Log n) Time
11 min read