C++ Program to Implement Min Heap

This C++ program displays the minimum heap method of arranging elements. Minimum Heap is a method of arranging elements in a binary search tree where value of the parent node is lesser than that of it’s child nodes.

Here is the source code of the C++ program to display the min heap after giving inputs of elements in array. This C++ program is successfully compiled and run on DevCpp, a C++ compiler. The program output is given below.

  1. /*
  2.  * C++ Program to Implement Min Heap
  3.  */
  4. #include <iostream>
  5. #include <conio.h>
  6. using namespace std;
  7. void min_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_minheap(int *a, int n)
  28. {
  29.     int i;
  30.     for(i = n/2; i >= 1; i--)
  31.     {
  32.         min_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_minheap(a, n);
  47.     cout<<"Min 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
11
enter element1
2
enter element2
16
enter element3
74
enter element4
58
enter element5
36
enter element6
4
enter element7
28
enter element8
15
enter element9
35
enter element10
82
enter element11
6
Min Heap
2
6
4
15
16
74
28
58
35
82
36

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

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

If you find any mistake above, kindly email to [email protected]

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.