-
Notifications
You must be signed in to change notification settings - Fork 3
/
BinaryHeap.h
146 lines (126 loc) · 2.66 KB
/
BinaryHeap.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
/*
BinaryHeap.h
堆的实现
*/
#ifndef BINARYHAEP_H_
#define BINARYHEAP_H_
#include <vector>
#include <algorithm>
#include "dsexception.h"
using std::vector;
template<typename Comparable>
class BinaryHeap
{
public:
explicit BinaryHeap(int capacity = 100)
: array(capacity + 1), currentSize{ 0 }
{}
explicit BinaryHeap(const vector<Comparable> & items)
: array(items.size() + 10), currentSize{ items.size() }
{
for (int i = 1; i <= currentSize; ++i)
{
array[i] = items[i - 1];
}
buildHeap();
}
bool isEmpty() const { return currentSize == 0; }
const Comparable & findMin() const
{
if (isEmpty())
{
throw UnderflowException{};
}
return array[1];
}
void insert(const Comparable & x)
{
if (currentSize == array.size() - 1) // 空间不足
{
array.resize(array.size() * 2);
}
int hole = ++currentSize;
Comparable copy = x;
array[0] = std::move(copy);
for (; x < array[hole / 2]; hole /= 2) // 向上冒
{
array[hole] = std::move(array[hole / 2]);
}
array[hole] = std::move(array[0]);
}
void insert(Comparable && x)
{
if (currentSize == array.size() - 1)
{
array.resize(array.size() * 2);
}
int hole = ++currentSize;
array[0] = std::move(x);
for (; x < array[hole / 2]; hole /= 2)
{
array[hole] = std::move(array[hole / 2]);
}
array[hole] = std::move(array[0]);
}
// 删除最小值
void deleteMin()
{
if (isEmpty())
{
throw UnderflowException{};
}
array[1] = std::move(array[currentSize--]);
percolateDown(1);
}
// 删除最小值,并且保存到minItem中
void deleteMin(Comparable & minItem)
{
if (isEmpty())
{
throw UnderflowException{};
}
minItem = std::move(array[1]);
array[1] = std::move(array[currentSize--]);
percolateDown(1);
}
void makeEmpty() { currentSize = 0; }
private:
int currentSize; // heap中元素数
vector<Comparable> array;
void buildHeap() // 用于创建heap
{
for (int i = currentSize / 2; i >= 1; --i)
{
percolateDown(i);
}
}
void percolateDown(int hole) // 向下渗入
{
Comparable tmp = std::move(array[hole]);
int child = 0;
while (hole* 2 <= currentSize)
{
child = hole * 2;
if (child != currentSize && array[child+1] < array[child])
{
++child;
}
if (array[child] < tmp)
{
array[hole] = std::move(array[child]);
hole = child;
}
else
{
break;
}
}
array[hole] = std::move(tmp);
}
/*
int parent(int n) { return n / 2; } // 父节点位置
int left(int n) { return 2 * n; } // 左节点位置
int right(int n) { return 2 * n + 1; } // 右节点位置
*/
};
#endif