Skip to content

Commit 3c88ecf

Browse files
committed
stl
1 parent 4197a3f commit 3c88ecf

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

stl/01-max-heap.cpp

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#include<iostream>
2+
using namespace std;
3+
4+
class PQ {
5+
public:
6+
int* arr;
7+
int size;
8+
PQ(int s) {
9+
arr = new int[s];
10+
size = 0;
11+
}
12+
int parent(int i) {
13+
return (i - 1) / 2;
14+
}
15+
int left(int i) {
16+
return 2 * i;
17+
}
18+
int right(int i) {
19+
return 2 * i + 1;
20+
}
21+
void heapify_down(int i) {
22+
int l = left(i);
23+
int r = right(i);
24+
int largest = i;
25+
// change sign to convert to min-heap
26+
if (l<size and arr[l]>arr[largest]) largest = l;
27+
if (r<size and arr[r]>arr[largest]) largest = r;
28+
if (largest != i) {
29+
swap(arr[i], arr[largest]);
30+
heapify_down(largest);
31+
}
32+
}
33+
void heapify_up(int i) {
34+
int p = parent(i);
35+
// > for min-heap
36+
if (p >= 0 and arr[p] < arr[i]) {
37+
swap(arr[i], arr[p]);
38+
heapify_up(p);
39+
}
40+
}
41+
void push(int val) {
42+
arr[size++] = val;
43+
heapify_up(size - 1);
44+
}
45+
void pop() {
46+
arr[0] = arr[--size];
47+
heapify_down(0);
48+
}
49+
int top() {
50+
return arr[0];
51+
}
52+
~PQ() {
53+
delete[]arr;
54+
}
55+
};
56+
int main() {
57+
PQ pq(10);
58+
59+
// Note: The element's value decides priority
60+
61+
pq.push(3);
62+
pq.push(2);
63+
pq.push(15);
64+
65+
cout << "Size is " << pq.size << endl;
66+
67+
cout << pq.top() << "\n ";
68+
pq.pop();
69+
70+
cout << pq.top() << ";\n";
71+
pq.pop();
72+
73+
pq.push(5);
74+
pq.push(4);
75+
pq.push(45);
76+
77+
cout << endl << "Size is " << pq.size << endl;
78+
79+
cout << pq.top() << " ";
80+
pq.pop();
81+
82+
cout << pq.top() << " ";
83+
pq.pop();
84+
85+
cout << pq.top() << " ";
86+
pq.pop();
87+
88+
cout << pq.top() << " ";
89+
pq.pop();
90+
91+
std::cout << pq.size;
92+
}

0 commit comments

Comments
 (0)