-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArraytoHeap.cpp
37 lines (29 loc) · 921 Bytes
/
ArraytoHeap.cpp
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
/***************************Normal Array to Heap*******************************/
void toHeap(vector<int>& v) {
int idx = v.size() / 2-1;
for (int i = idx; i >= 0; i--) {
MaxHeapify(v, i);
}
}
void MaxHeapify(vector<int>& v,int idx) {
for (int i = idx; i < v.size() / 2; i++) {
int left = 2 * i + 1, right = 2 * i + 2;
if (v[i] < max(v[left], v[right])) {
if (v[i] < v[left])
swap(v[i], v[left]);
if (right < v.size() && v[i] < v[right])
swap(v[i], v[right]);
}
}
}
void MinHeapify(vector<int>& v, int idx) {
for (int i = idx; i < v.size() / 2; i++) {
int left = 2 * i + 1, right = 2 * i + 2;
if (v[i] > max(v[left], v[right])) {
if (v[i] > v[left])
swap(v[i], v[left]);
if (right < v.size() && v[i] > v[right])
swap(v[i], v[right]);
}
}
}