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.
/*
* C++ Program to Implement Min Heap
*/
#include <iostream>
#include <conio.h>
using namespace std;
void min_heapify(int *a,int i,int n)
{
int j, temp;
temp = a[i];
j = 2 * i;
while (j <= n)
{
if (j < n && a[j+1] < a[j])
j = j + 1;
if (temp < a[j])
break;
else if (temp >= a[j])
{
a[j/2] = a[j];
j = 2 * j;
}
}
a[j/2] = temp;
return;
}
void build_minheap(int *a, int n)
{
int i;
for(i = n/2; i >= 1; i--)
{
min_heapify(a,i,n);
}
}
int main()
{
int n, i, x;
cout<<"enter no of elements of array\n";
cin>>n;
int a[20];
for (i = 1; i <= n; i++)
{
cout<<"enter element"<<(i)<<endl;
cin>>a[i];
}
build_minheap(a, n);
cout<<"Min Heap\n";
for (i = 1; i <= n; i++)
{
cout<<a[i]<<endl;
}
getch();
}
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.
Related Posts:
- Check Computer Science Books
- Practice Computer Science MCQs
- Check Data Structure Books
- Practice Programming MCQs
- Check Programming Books