
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Merge two binary Max Heaps using C++.
Problem statement
Given two binary max heaps as arrays, merge the into single max heap.
Heap1[] = {20, 17, 15, 10} Heap2[] = {19, 13, 7} Result[] = {20, 19, 15, 13, 17, 7, 10}
Algorithm
1.Create an array to store result 2. Copy both given arrays one by one to result array 3. Build heap to construct full merged max heap
Example
#include <iostream> #include <algorithm> #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; void heapify(int *arr, int n, int idx){ if (idx >= n) { return; } int l = 2 * idx + 1; int r = 2 * idx + 2; int max; if (l < n && arr[l] > arr[idx]) { max = l; } else { max = idx; } if (r < n && arr[r] > arr[max]) { max = r; } if (max != idx) { swap(arr[max], arr[idx]); heapify(arr, n, max); } } void createMaxHeap(int *arr, int n){ for (int i = n / 2 - 1; i >= 0; --i) { heapify(arr, n, i); } } void mergeMaxHeaps(int *arr1, int n1, int *arr2, int n2, int *result){ merge(arr1, arr1 + n1, arr2, arr2 + n2, result); createMaxHeap(result, n1 + n2); } void displayHeap(int *arr, int n){ for (int i = 0; i < n; ++i) { cout << arr[i] << " "; } cout << endl; } int main(){ int heap1[] = {20, 17, 15, 10}; int heap2[] = {19, 13, 7}; int result[SIZE(heap1) + SIZE(heap2)]; cout << "First max heap: " << endl; displayHeap(heap1, SIZE(heap1)); cout << "Second max heap: " << endl; displayHeap(heap2, SIZE(heap2)); mergeMaxHeaps(heap1, SIZE(heap1), heap2, SIZE(heap2), result); cout << "Merged max heap: " << endl; displayHeap(result, SIZE(result)); return 0; }
Output
When you compile and execute the above program. It generates the following output −
First max heap: 20 17 15 10 Second max heap: 19 13 7 Merged max heap: 20 19 15 13 17 7 10
- Related Articles
- Min-Max Heaps
- Merge Two Binary Trees in C++
- Symmetric Min-Max Heaps
- Program to merge two binary trees in C++
- Merge two sorted arrays using C++.
- Merge two arrays using C# AddRange() method
- Merge two sorted linked lists using C++.
- Merge two sorted arrays into a list using C#
- Merge contents of two files into a third file using C
- C# program to merge two Dictionaries
- Merge two sorted arrays in C#
- Merge Overlapping Intervals using C++.
- Merge two sorted arrays in Python using heapq?
- Largest Merge of Two Strings in C++
- C# Program to Merge Two Hashtable Collections

Advertisements