Merge k Sorted Arrays Using Min Heap
Last Updated :
23 Aug, 2024
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
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
Python
# 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(' '));
OutputMerged array is
1 2 6 9 12 23 34 90 2000
Time Complexity: O(N log k) Here N is total number of elements in all input arrays.
Auxiliary Space: O(k)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read