1// C++ program to show that priority_queue is by
2// default a Max Heap
3#include <bits/stdc++.h>
4using namespace std;
5
6// Driver code
7int main ()
8{
9 // Creates a max heap
10 priority_queue <int> pq;
11 pq.push(5);
12 pq.push(1);
13 pq.push(10);
14 pq.push(30);
15 pq.push(20);
16
17 // One by one extract items from max heap
18 while (pq.empty() == false)
19 {
20 cout << pq.top() << " ";
21 pq.pop();
22 }
23
24 return 0;
25}
26
1#include <iostream>
2using namespace std;
3void max_heap(int *a, int m, int n) {
4 int j, t;
5 t = a[m];
6 j = 2 * m;
7 while (j <= n) {
8 if (j < n && a[j+1] > a[j])
9 j = j + 1;
10 if (t > a[j])
11 break;
12 else if (t <= a[j]) {
13 a[j / 2] = a[j];
14 j = 2 * j;
15 }
16 }
17 a[j/2] = t;
18 return;
19}
20void build_maxheap(int *a,int n) {
21 int k;
22 for(k = n/2; k >= 1; k--) {
23 max_heap(a,k,n);
24 }
25}
26int main() {
27 int n, i;
28 cout<<"enter no of elements of array\n";
29 cin>>n;
30 int a[30];
31 for (i = 1; i <= n; i++) {
32 cout<<"enter elements"<<" "<<(i)<<endl;
33 cin>>a[i];
34 }
35 build_maxheap(a,n);
36 cout<<"Max Heap\n";
37 for (i = 1; i <= n; i++) {
38 cout<<a[i]<<endl;
39 }
40}