-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeHeap.h
59 lines (48 loc) · 1.48 KB
/
theHeap.h
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
#include <iostream>
#include <vector>
#pragma once
using namespace std;
class minHeap {
int parent(int index) {
return (index - 1) / 2;
}
void heapifyUp(int index) {
while (index > 0 && theheap[index].second < theheap[parent(index)].second) {
swap(theheap[index], theheap[parent(index)]);
index = parent(index);
}
}
void heapifyDown(int index) {
int smallest = index; // Initialize largest as root
int l = 2 * index + 1; // left = 2*i + 1
int r = 2 * index + 2; // right = 2*i + 2
// If left child is smaller than root
if (l < theheap.size() && theheap[l].second < theheap[smallest].second)
smallest = l;
// If right child is smaller than smaller so far
if (r < theheap.size() && theheap[r].second < theheap[smallest].second)
smallest = r;
// If largest is not root
if (smallest != index) {
swap(theheap[index], theheap[smallest]);
heapifyDown(smallest);
}
}
public:
vector<pair<int, float>> theheap;
void InsertHeap(pair<int, float> interval) {
theheap.push_back(interval);
heapifyUp(theheap.size() - 1);
}
pair<int, float> getMin() {
return theheap[0];
}
void extractMin() {
if(theheap.empty()) {
throw:: out_of_range("empty");
}
theheap[0] = theheap.back();
theheap.pop_back();
heapifyDown(0);
}
};