Merge Two Binary Max Heaps (original) (raw)

Last Updated : 23 Jul, 2025

Given two binary max heaps, the task is to merge the given heaps to form a new max heap.

**Examples :

**Input: a[] = {10, 5, 6, 2}, b[] = {12, 7, 9}
**Output: {12, 10, 9, 2, 5, 7, 6}

[Merge-two-max-heaps-(1)](Merge Two Binary Max Heaps)

Merge Two Binary Max Heaps

**Input: a[] = {2, 5, 1, 9, 12}, b[] = {3, 7, 4, 10}
**Output: {12, 10, 7, 9, 5, 3, 1, 4, 2}

Table of Content

[Naive Approach] Merge using extra Max Heap - O((N + M)*log(N + M)) Time and O(N + M) Space:

The property of Max Heap is that the top of any Max Heap is always the largest element. We will use this property to merge the given binary Max Heaps.

To do this:

Below is the implementation of the above approach:

C++ `

// C++ Program to merge two binary max heaps

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

// function to merge max heaps vector mergeHeaps(vector& a, vector& b, int n, int m) { // Max Heap to store all the elements priority_queue maxHeap;

// Insert all the elements of first array
for (int i = 0; i < n; i++) {
    maxHeap.push(a[i]);
}

// Insert all the elements of second array
for (int i = 0; i < m; i++) {
    maxHeap.push(b[i]);
}

vector<int> merged;
// Push all the elements from the max heap
while (!maxHeap.empty()) {
    merged.push_back(maxHeap.top());
    maxHeap.pop();
}
return merged;

}

int main() { // Sample Input vector a = { 10, 5, 6, 2 }; vector b = { 12, 7, 9 }; int n = a.size(), m = b.size();

vector<int> merged = mergeHeaps(a, b, n, m);

for (int i = 0; i < n + m; i++)
    cout << merged[i] << " ";
return 0;

}

Java

import java.util.*; public class GFG {

// Function to merge max heaps
public static int[] mergeHeaps(int[] a, int[] b, int n, int m) {
    // Max Heap to store all the elements
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>((x, y) -> y - x);

    // Insert all the elements for first array
    for (int i = 0; i < n; i++) {
        maxHeap.add(a[i]);
    }

    // Insert all the elements for second array
    for (int i = 0; i < m; i++) {
        maxHeap.add(b[i]);
    }

    int[] merged = new int[n + m];
    int index = 0;
    // Push all the elements from the max heap
    while (!maxHeap.isEmpty()) {
        merged[index++] = maxHeap.poll();
    }
    return merged;
}

public static void main(String[] args) {
    // Sample Input
    int[] a = { 10, 5, 6, 2 };
    int[] b = { 12, 7, 9 };
    int n = a.length;
    int m = b.length;

    int[] merged = mergeHeaps(a, b, n, m);

    for (int i = 0; i < n + m; i++) {
        System.out.print(merged[i] + " ");
    }
}

}

Python

import heapq

def merge_heaps(a, b): # Create a max heap by negating the elements max_heap = []

# Insert all elements of first list into the max heap
for num in a:
    heapq.heappush(max_heap, -num)

# Insert all elements of second list into the max heap
for num in b:
    heapq.heappush(max_heap, -num)

merged = []
# Extract elements from the max heap
while max_heap:
    merged.append(-heapq.heappop(max_heap))

return merged

Sample Input

a = [10, 5, 6, 2] b = [12, 7, 9]

merged = merge_heaps(a, b)

for num in merged: print(num, end=' ')

JavaScript

function mergeHeaps(a, b) { // Max Heap to store all the elements let maxHeap = [];

// Insert all the elements of the first array
for (let num of a) {
    maxHeap.push(num);
}

// Insert all the elements of the second array
for (let num of b) {
    maxHeap.push(num);
}

// Convert array into a max heap
maxHeap.sort((x, y) => y - x);

return maxHeap;

}

// Sample Input let a = [10, 5, 6, 2]; let b = [12, 7, 9];

let merged = mergeHeaps(a, b);

console.log(merged.join(' '));

`

**Time Complexity: O((N + M)*log(N + M)), where N is the size of a[] and M is the size of b[].

**Auxiliary Space: O(N + M), which is the size of the resultant merged binary max heap

[Expected Approach] Merge and then Build Heap - O(N + M) Time and O(N + M) Space:

Another approach is that instead of creating a max heap from the start, flatten the given max heap into arrays and merge them. Then max heapify this merged array.

The benefit of doing so, is that, instead of taking O(log N+M) time everytime to apply heapify operation as shown in above approach, this approach will take only O(N+M) time once to build the final heap.

Below is the implementation of the above approach:

C++ `

// C++ program to merge two max heaps

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

// Standard heapify function to heapify a // subtree rooted under idx. It assumes // that subtrees of node are already heapified. void maxHeapify(vector& arr, int n, int idx) { // Find largest of node and its children if (idx >= n) return;

int l = 2 * idx + 1;
int r = 2 * idx + 2;
int max = idx;
if (l < n && arr[l] > arr[idx])
    max = l;
if (r < n && arr[r] > arr[max])
    max = r;

// Put maximum value at root and
// recur for the child with the
// maximum value
if (max != idx) {
    swap(arr[max], arr[idx]);
    maxHeapify(arr, n, max);
}

}

// Builds a max heap of given arr[0..n-1] void buildMaxHeap(vector& arr, int n) { // building the heap from first non-leaf // node by calling max heapify function for (int i = n / 2 - 1; i >= 0; i--) maxHeapify(arr, n, i); }

// Merges max heaps a[] and b[] into merged[] vector mergeHeaps(vector& a, vector& b, int n, int m) { // Copy elements of a[] and b[] one by one // to merged[] vector merged(n + m, 0); for (int i = 0; i < n; i++) merged[i] = a[i]; for (int i = 0; i < m; i++) merged[n + i] = b[i];

// build heap for the modified array of
// size n+m
buildMaxHeap(merged, n + m);
return merged;

}

// Driver's code int main() { // Sample Input vector a = { 10, 5, 6, 2 }; vector b = { 12, 7, 9 };

int n = a.size();
int m = b.size();

// Function call
vector<int> merged = mergeHeaps(a, b, n, m);

for (int i = 0; i < n + m; i++)
    cout << merged[i] << " ";

return 0;

}

Java

// Java Program to merge two max heaps

import java.util.Arrays;

public class MergeMaxHeaps {

// Standard heapify function to heapify a subtree rooted
// under idx. It assumes that subtrees of node are
// already heapified.
public static void maxHeapify(int[] arr, int n, int idx)
{
    if (idx >= n)
        return;

    int l = 2 * idx + 1;
    int r = 2 * idx + 2;
    int max = idx;

    if (l < n && arr[l] > arr[idx])
        max = l;
    if (r < n && arr[r] > arr[max])
        max = r;

    if (max != idx) {
        int temp = arr[max];
        arr[max] = arr[idx];
        arr[idx] = temp;
        maxHeapify(arr, n, max);
    }
}

// Builds a max heap of given arr[0..n-1]
public static void buildMaxHeap(int[] arr, int n)
{
    for (int i = n / 2 - 1; i >= 0; i--) {
        maxHeapify(arr, n, i);
    }
}

// Merges max heaps a[] and b[] into merged[]
public static int[] mergeHeaps(int[] a, int[] b, int n,
                               int m)
{
    // Merge both the arrays
    int[] merged = new int[n + m];
    for (int i = 0; i < n; i++)
        merged[i] = a[i];
    for (int i = 0; i < m; i++)
        merged[n + i] = b[i];

    buildMaxHeap(merged, n + m);
    return merged;
}

public static void main(String[] args)
{
    // Sample Input
    int[] a = { 10, 5, 6, 2 };
    int[] b = { 12, 7, 9 };

    int n = a.length;
    int m = b.length;

    // Function call
    int[] merged = mergeHeaps(a, b, n, m);

    for (int i = 0; i < n + m; i++)
        System.out.print(merged[i] + " ");
}

}

Python

Python3 program to merge two Max heaps

Standard heapify function to heapify a subtree

rooted under idx. It assumes that subtrees of node

are already heapified

def maxHeapify(arr, n, idx): if idx >= n: return

l = 2 * idx + 1
r = 2 * idx + 2
max_idx = idx

if l < n and arr[l] > arr[max_idx]:
    max_idx = l
if r < n and arr[r] > arr[max_idx]:
    max_idx = r

if max_idx != idx:
    arr[max_idx], arr[idx] = arr[idx], arr[max_idx]
    maxHeapify(arr, n, max_idx)

Builds a max heap of given arr[0..n-1]

def buildMaxHeap(arr, n): for i in range(n // 2 - 1, -1, -1): maxHeapify(arr, n, i)

Merges max heaps a[] and b[] into merged[]

def mergeHeaps(a, b, n, m): merged = a + b l = len(merged) buildMaxHeap(merged, l) return merged

Sample Input

a = [10, 5, 6, 2] b = [12, 7, 9]

Function call

merged = mergeHeaps(a, b, len(a), len(b))

for x in merged: print(x, end = " ")

C#

// C# program to merge two max heaps

using System; using System.Collections.Generic;

public class GFG { // Standard heapify function to heapify a subtree rooted // under idx. It assumes that subtrees of node are // already heapified. public static void MaxHeapify(List arr, int n, int idx) { if (idx >= n) return;

    int l = 2 * idx + 1;
    int r = 2 * idx + 2;
    int max = idx;

    if (l < n && arr[l] > arr[max])
        max = l;
    if (r < n && arr[r] > arr[max])
        max = r;

    if (max != idx) {
        int temp = arr[max];
        arr[max] = arr[idx];
        arr[idx] = temp;
        MaxHeapify(arr, n, max);
    }
}

// Builds a max heap of given arr[0..n-1]
public static void BuildMaxHeap(List<int> arr, int n)
{
    for (int i = n / 2 - 1; i >= 0; i--)
        MaxHeapify(arr, n, i);
}

// Merges max heaps a[] and b[] into merged[]
public static List<int>
MergeHeaps(List<int> a, List<int> b, int n, int m)
{
    List<int> merged = new List<int>(n + m);

    for (int i = 0; i < n; i++)
        merged.Add(a[i]);
    for (int i = 0; i < m; i++)
        merged.Add(b[i]);

    BuildMaxHeap(merged, n + m);
    return merged;
}

public static void Main()
{
    // Sample Input
    List<int> a = new List<int>{ 10, 5, 6, 2 };
    List<int> b = new List<int>{ 12, 7, 9 };

    int n = a.Count;
    int m = b.Count;

    // Function call
    List<int> merged = MergeHeaps(a, b, n, m);

    foreach(int num in merged) Console.Write(num + " ");
}

}

JavaScript

// Javascript program to merge two max heaps.

// Standard heapify function to heapify a // subtree rooted under idx. It assumes // that subtrees of node are already heapified. function maxHeapify(arr, n, idx) { if (idx >= n) return;

let l = 2 * idx + 1;
let r = 2 * idx + 2;
let max = idx;

if (l < n && arr[l] > arr[idx]) max = l;
if (r < n && arr[r] > arr[max]) max = r;

if (max !== idx) {
    [arr[max], arr[idx]] = [arr[idx], arr[max]];
    maxHeapify(arr, n, max);
}

}

// Builds a max heap of given arr[0..n-1] function buildMaxHeap(arr, n) { for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { maxHeapify(arr, n, i); } }

// Merges max heaps a[] and b[] into merged[] function mergeHeaps(a, b) { let n = a.length; let m = b.length; let merged = new Array(n + m);

for (let i = 0; i < n; i++) merged[i] = a[i];
for (let i = 0; i < m; i++) merged[n + i] = b[i];

buildMaxHeap(merged, n + m);
return merged;

}

// Driver's code // Sample Input let a = [10, 5, 6, 2]; let b = [12, 7, 9];

// Function call let merged = mergeHeaps(a, b);

for (let i = 0; i < merged.length; i++) { console.log(merged[i] + " "); }

`

**Time Complexity: O(N + M)
**Auxiliary Space: O(N + M)

**Time Complexity: O(N + M), where N is the size of a[] and M is the size of b[].

**Auxiliary Space: O(N + M), which is the size of the resultant merged binary max heap