-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMaxHeap.cpp
More file actions
89 lines (87 loc) · 1.07 KB
/
MaxHeap.cpp
File metadata and controls
89 lines (87 loc) · 1.07 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
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
#include <vector>
#include <climits>
using namespace std;
class MaxHeap
{
vector<int> v;
int N;
void swim(int k)
{
while(k > 1)
{
if(less(k/2,k))
swap(v[k/2],v[k]);
else break;
k = k/2;
}
}
void sink(int k)
{
int j;
while(2*k <= N)
{
j = 2*k;
if(j < N && less(j,j+1))
j++;
if(!less(k,j)) break;
swap(v[k],v[j]);
k = j;
}
}
bool less(int i,int j)
{
return (v[i] < v[j]);
}
public:
MaxHeap()
{
v.push_back(0);
N = 0;
}
bool isempty()
{
return (N==0);
}
int getMax()
{
if(N == 0)
{
cout << "Heap Empty!!!\n";
return INT_MIN;
}
return v[1];
}
void insert(int val)
{
if(v.size() > N+1)
v[N+1] = val;
else
v.push_back(val);
N++;
swim(N);
}
int delMax()
{
swap(v[1],v[N]);
N--;
sink(1);
return v[N+1];
}
};
int main()
{
MaxHeap pq;
pq.insert(2);
pq.insert(5);
pq.insert(4);
pq.insert(6);
pq.insert(3);
cout << pq.delMax() << ' ';
cout << pq.delMax() << ' ';
pq.insert(10);
pq.insert(8);
cout << pq.delMax() << ' ';
cout << pq.delMax() << ' ';
// 6 5 10 8
}