-
Notifications
You must be signed in to change notification settings - Fork 0
/
heap.cc
74 lines (59 loc) · 1.4 KB
/
heap.cc
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
#include <iostream>
#include <vector>
class MaxHeap {
private:
std::vector<int> heap;
void heapifyUp(int index) {
int parent = (index - 1) / 2;
while (index > 0 && heap[index] > heap[parent]) {
std::swap(heap[index], heap[parent]);
index = parent;
parent = (index - 1) / 2;
}
}
void heapifyDown(int index) {
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
int largest = index;
if (leftChild < heap.size() && heap[leftChild] > heap[largest]) {
largest = leftChild;
}
if (rightChild < heap.size() && heap[rightChild] > heap[largest]) {
largest = rightChild;
}
if (largest != index) {
std::swap(heap[index], heap[largest]);
heapifyDown(largest);
}
}
public:
void insert(int value) {
heap.push_back(value);
heapifyUp(heap.size() - 1);
}
int extractMax() {
if (heap.empty()) {
throw std::runtime_error("Heap is empty");
}
int max = heap[0];
heap[0] = heap.back();
heap.pop_back();
heapifyDown(0);
return max;
}
bool isEmpty() const { return heap.empty(); }
};
int main() {
MaxHeap maxHeap;
maxHeap.insert(5);
maxHeap.insert(2);
maxHeap.insert(10);
maxHeap.insert(3);
maxHeap.insert(8);
std::cout << "大根堆中的元素: ";
while (!maxHeap.isEmpty()) {
std::cout << maxHeap.extractMax() << " ";
}
std::cout << std::endl;
return 0;
}