

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to Implement Max Heap
A Binary Heap is a complete binary tree which is either Min Heap or Max Heap. In a Max Binary Heap, the key at root must be maximum among all keys present in Binary Heap. This property must be recursively true for all nodes in Binary Tree. Min Binary Heap is similar to MinHeap.
Algorithm
For max_heap:
Begin Declare function max_heap () Declare j, t of the integer datatype. Initialize t = a[m]. j = 2 * m; while (j <= n) do if (j < n && a[j+1] > a[j]) then j = j + 1 if (t > a[j]) then break else if (t <= a[j]) then a[j / 2] = a[j] j = 2 * j a[j/2] = t return End.
For build_maxheap:
Begin Declare function build_maxheap(int *a,int n). Declare k of the integer datatype. for(k = n/2; k >= 1; k--) Call function max_heap(a,k,n) End.
Example
#include <iostream> using namespace std; void max_heap(int *a, int m, int n) { int j, t; t = a[m]; j = 2 * m; while (j <= n) { if (j < n && a[j+1] > a[j]) j = j + 1; if (t > a[j]) break; else if (t <= a[j]) { a[j / 2] = a[j]; j = 2 * j; } } a[j/2] = t; return; } void build_maxheap(int *a,int n) { int k; for(k = n/2; k >= 1; k--) { max_heap(a,k,n); } } int main() { int n, i; cout<<"enter no of elements of array\n"; cin>>n; int a[30]; for (i = 1; i <= n; i++) { cout<<"enter elements"<<" "<<(i)<<endl; cin>>a[i]; } build_maxheap(a,n); cout<<"Max Heap\n"; for (i = 1; i <= n; i++) { cout<<a[i]<<endl; } }
Output
enter no of elements of array 5 enter elements 1 7 enter elements 2 6 enter elements 3 2 enter elements 4 1 enter elements 5 4 Max Heap 7 6 2 1 4
- Related Questions & Answers
- C++ Program to Implement Heap Sort
- C++ Program to Implement Binary Heap
- C++ Program to Implement Min Heap
- Convert min Heap to max Heap in C++
- Convert BST to Max Heap in C++
- Program to check heap is forming max heap or not in Python
- Max Heap in Java
- Is Max Heap in Python?
- Minimum element in a max heap in C++.
- K-th Greatest Element in a Max-Heap in C++
- Deletion from a Max Heap in Data Structure
- Insertion into a Max Heap in Data Structure
- Implement MySQL INSERT MAX()+1?
- C++ Program to Implement Vector
- C# program to implement FizzBuzz
Advertisements