C++ Program to Implement Max Heap

This C++ program, displays the maximum heap in which each node of a binary tree is greater than or equal to it’s child nodes.

Here is the source code of the C++ program which takes the values of array as input and returns the elements as they are structured in the maximum heap model. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is also shown below.

  1. /*
  2. * C++ Program to Implement Max Heap
  3.  */
  4. #include <iostream>
  5. #include <conio.h>
  6. using namespace std;
  7. void max_heapify(int *a, int i, int n)
  8. {
  9.     int j, temp;
  10.     temp = a[i];
  11.     j = 2 * i;
  12.     while (j <= n)
  13.     {
  14.         if (j < n && a[j+1] > a[j])
  15.             j = j + 1;
  16.         if (temp > a[j])
  17.             break;
  18.         else if (temp <= a[j])
  19.         {
  20.             a[j / 2] = a[j];
  21.             j = 2 * j;
  22.         }
  23.     }
  24.     a[j/2] = temp;
  25.     return;
  26. }
  27. void build_maxheap(int *a,int n)
  28. {
  29.     int i;
  30.     for(i = n/2; i >= 1; i--)
  31.     {
  32.         max_heapify(a,i,n);
  33.     }
  34. }
  35. int main()
  36. {
  37.     int n, i, x;
  38.     cout<<"enter no of elements of array\n";
  39.     cin>>n;
  40.     int a[20];
  41.     for (i = 1; i <= n; i++)
  42.     {
  43.         cout<<"enter element"<<(i)<<endl;
  44.         cin>>a[i];
  45.     }
  46.     build_maxheap(a,n);
  47.     cout<<"Max Heap\n";
  48.     for (i = 1; i <= n; i++)
  49.     {
  50.         cout<<a[i]<<endl;
  51.     }
  52.     getch();
  53. }

Output
enter no of elements of array
7
enter element1
5
enter element2
9
enter element3
6
enter element4
7
enter element5
1
enter element6
3
enter element7
8
Max Heap
9
7
8
5
1
3
6

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.