-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHeap.cpp
79 lines (65 loc) · 1.21 KB
/
Heap.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
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
#include<iostream>
#include<vector>
using namespace std;
/**
*
* Implementation of heap data structure in C++
*
*/
class Heap {
private:
vector<int> heap;
public:
void heapify(int i) {
int size = heap.size();
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && heap[l] > heap[largest]) {
largest = l;
}
if (r < size && heap[r] > heap[largest]) {
largest = r;
}
if (largest != i) {
swap(heap[i], heap[largest]);
heapify(largest);
}
}
void insert(int item) {
int size = heap.size();
if (size == 0) {
heap.push_back(item);
} else {
heap.push_back(item);
for (int i = size / 2; i>=0; i--) {
heapify(i);
}
}
}
void remove(int num) {
int size = heap.size();
int i;
for (i = 0; i < size; i++){
if (num == heap[i])
break;
}
swap(heap[i], heap[size - 1]);
heap.pop_back();
for (int i = size / 2 - 1; i >= 0; i--){
heapify(i);
}
}
void print() {
for (int i = 0; i < heap.size(); ++i)
cout << heap[i] << " ";
cout << "\n";
}
};
int main () {
Heap heap;
heap.insert(1);
heap.insert(2);
heap.insert(3);
heap.print();
}