-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMax Heap.cpp
More file actions
78 lines (70 loc) · 1.27 KB
/
Max Heap.cpp
File metadata and controls
78 lines (70 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<iostream>
using namespace std;
void swap(int *a, int *b)
{
int c;
c=*a;
*a=*b;
*b=c;
}
class max_h{
int size,rear;
int *m_heap;
public:
//constructor
max_h(int s)
{
rear=0;
size=s+1;
m_heap = new int[s+1];
*m_heap=0;
}
void perculate_up(int child_ind)
{
if(child_ind>1)
{
if(*(m_heap+child_ind/2)<*(m_heap+child_ind))
{
swap((m_heap+child_ind/2),(m_heap+child_ind));
perculate_up(child_ind/2);
}
}
}
void insert(int val)
{
if(rear<size)
{
++rear;
*(m_heap+rear) = val;
perculate_up(rear);
}
else
{
cout<<"heap is full right now. cannot add more elements\n";
}
}
void print_heap()
{
for(int i=1;i<size;++i)
cout<<*(m_heap+i)<<" ";
}
};
int main()
{
//max_h <int> maxheap;
max_h tree(13);
tree.insert(35);
tree.insert(33);
tree.insert(42);
tree.insert(10);
tree.insert(14);
tree.insert(19);
tree.insert(27);
tree.insert(44);
tree.insert(26);
tree.insert(31);
tree.insert(8);
tree.insert(5);
tree.insert(50);
tree.print_heap();
}