[AlgoExpert] Min Heap Construction

Min Heap Construction

  • Space : O(n)
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
#include <vector>
using namespace std;

// Do not edit the class below except for the buildHeap,
// siftDown, siftUp, peek, remove, and insert methods.
// Feel free to add new properties and methods to the class.
class MinHeap {
public:
vector<int> heap;

MinHeap(vector<int> vector) { // O(n logn)
buildHeap(vector);
}

void buildHeap(vector<int> &vector) {
for(auto& a : vector)
insert(a);
}

void siftDown() { // O(logn)
int i = 0;
while(true) {
int child1 = i * 2 + 1, child2 = i * 2 + 2;
if(child1 >= heap.size()) return;
if(child2 >= heap.size()) {
if(heap[child1] < heap[i]) {
swap(heap[child1], heap[i]);
i = child1;
} else return;
} else {
if(heap[child1] > heap[child2]) {
if(heap[child2] < heap[i]) {
swap(heap[child2], heap[i]);
i = child2;
} else return;
} else {
if(heap[child1] < heap[i]) {
swap(heap[child1], heap[i]);
i = child1;
} else return;
}
}
}
}

void siftUp() { // O(logn)
int i = heap.size() - 1;
while(i) {
int par = (i - 1)/ 2;
if(heap[par] > heap[i]) {
swap(heap[par], heap[i]);
i = par;
} else return;
}
}

int peek() { // O(1)
if(heap.empty()) return -1;
return heap[0];
}

int remove() { // O(logn)
int res = heap[0];
heap[0] = heap.back();
heap.pop_back();
siftDown();
return res;
}

void insert(int value) { // O(logn)
heap.push_back(value);
siftUp();
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/14/PS/AlgoExpert/min-heap-construction/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.